我遇到了实体框架如何推断实体关系的概念障碍。所以,虽然我已经解决了我的问题,但我不明白为什么它能工作。
我有以下实体,这里是简化形式,来自几何类库。
行类,为了简洁,隐藏主键/外键属性,并专注于问题:
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; }
}
}
linesegement类,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 }; }
}
}
这是我的理解,实体框架忽略getter-only属性,只映射属性与getter和setter。但是,为了避免出现
错误,无法确定相关操作的有效顺序。依赖关系可能由于外键约束、模型需求或存储生成的值而存在。
在插入linessegment到数据库(线和矢量工作良好),我必须有以下在我的模型创建:
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);
}
大多数对我来说是有意义的,但是对于实体框架理解我的模型而不产生上面引用的错误,为什么我必须包括最后一个语句?
似乎Entity Framework会自动忽略类型字符串、基本类型和枚举类型的仅getter属性。在所有其他情况下,您必须使用.Ignore()
方法或[NotMapped]
注释显式忽略它们。