【发布时间】:2021-04-01 00:40:17
【问题描述】:
假设我要代表以下业务领域:
- 每辆车都有一个里程表
- 每个里程表都属于一辆车
- 汽车知道里程表
- 里程表不了解汽车
我理想的 OOP 表示是这样的
public class Car
{
public Guid Id { get; }
public Odomoeter Odomoeter { get; }
private Car(Guid id, Odometer odometer)
{
this.Id = id;
this.Odometer = odometer;
}
public static Car CreateNew(Guid id) => new Car(id, Odometer.CreateNew(id));
}
public class Odometer
{
public int Miles
{
get => this._miles;
set
{
if (value < this._miles)
throw new InvalidOperationException("Cannot wind back odometer! ILLEGAL!");
this._miles = value;
}
}
private int _miles;
private Odometer(Guid id, int miles)
{
this.Id = id;
this._miles = miles;
}
public static Odometer CreateNew(Guid id) => new Odometer(id, 0);
}
而不是像贫血一样
public class Car
{
public Guid Id { get; set; }
public Odomoeter Odomoeter { get; set; }
public Guid OdometerId { get; set; }
}
public class Odometer
{
public Guid Id { get; set; }
public int Miles { get; set; }
public Car Car { get; set; }
public Guid CarId { get; set; }
}
但是,我不确定这是否可以通过HasOne...WithOne..etc. 流利的语法实现。看来您需要在父母和孩子之间进行双向参考。我知道 SQL 表应该是什么样子,非常简单:
Car
=================
Id | OdometerId
Odometer
=================
Id | Miles
但是,将它连接到我的封装模型一直很痛苦。
【问题讨论】:
标签: c# sql entity-framework orm entity-framework-core