【发布时间】:2015-12-05 13:15:02
【问题描述】:
我遇到了实体框架如何推断实体关系的概念障碍。因此,虽然我已经解决了我的问题,但它为什么起作用对我来说没有意义。
我有以下实体,这里是简化形式,来自Geometry Class Library。
Line 类,为简洁起见隐藏了主键/外键属性并专注于问题:
public class Line
{
public virtual Point BasePoint
{
get { return _basePoint; }
set { _basePoint = value; }
}
private Point _basePoint;
public virtual Direction Direction
{
get { return _direction; }
set { _direction = value; }
}
private Direction _direction;
}
Vector 类,Line 的子类,也隐藏了主/外键属性:
public class Vector : Line
{
public virtual Distance Magnitude
{
get { return _magnitude; }
set { _magnitude = value; }
}
private Distance _magnitude;
public virtual Point EndPoint
{
get { return new Point(XComponent, YComponent, ZComponent) + BasePoint; }
}
}
LineSegment 类,Vector 的子类,也隐藏了主/外键属性:
public partial class LineSegment : Vector
{
public virtual Distance Length
{
get { return base.Magnitude; }
set { base.Magnitude = value; }
}
public List<Point> EndPoints
{
get { return new List<Point>() { BasePoint, EndPoint }; }
}
}
据我了解,Entity Framework 忽略 getter-only 属性,只使用 getter 和 setter 映射属性。但是,为了避免出错
无法确定相关操作的有效顺序。由于外键约束、模型要求或存储生成的值,可能存在依赖关系。
在将 LineSegment 插入数据库时(Line 和 Vector 工作正常),我的模型创建中必须包含以下内容:
protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
// ...
// Set up Line model
modelBuilder.Entity<Line>()
.HasKey(line => line.DatabaseId);
modelBuilder.Entity<Line>()
.HasRequired(line => line.BasePoint)
.WithMany()
.HasForeignKey(line => line.BasePoint_DatabaseId); // Identify foreign key field
modelBuilder.Entity<Line>()
.HasRequired(line => line.Direction)
.WithMany()
.HasForeignKey(line => line.Direction_DatabaseId); // Identify foreign key field
modelBuilder.Entity<Vector>()
.HasRequired(vector => vector.Magnitude)
.WithMany()
.HasForeignKey(vector => vector.Magnitude_DatabaseId); // Identify foreign key field
modelBuilder.Entity<LineSegment>()
.Ignore(lineSegment => lineSegment.Length);
modelBuilder.Entity<LineSegment>() // Why this? EndPoints is a getter only property
.Ignore(lineSegment => lineSegment.EndPoints);
}
其中大部分对我来说是有意义的,但要让实体框架理解我的模型而不产生上面引用的错误,为什么我必须包含最后一条语句?
【问题讨论】:
标签: c# entity-framework mapping entity-framework-6