我在 Entity Framework 如何推断实体关系方面遇到了概念障碍。因此,虽然我已经解决了我的问题,但我不明白为什么它会起作用。
我有以下实体,这里是简化形式,来自 Geometry Class Library .
行类,为简洁起见隐藏主键/外键属性并关注问题:
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 的属性。但是,为了避免出现错误
Unable to determine a valid ordering for dependent operations. Dependencies may exist due to foreign key constraints, model requirements, or store-generated values.
在将 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);
}
其中大部分内容对我来说都有意义,但是为了让 Entity Framework 理解我的模型并且不产生上面引用的错误,为什么我必须包含最后一条语句?
最佳答案
Entity Framework 似乎自动忽略了字符串类型、基本类型和枚举类型的 getter-only 属性。在所有其他情况下,您必须使用 .Ignore()
方法或 [NotMapped]
注释显式忽略它们。
关于c# - Entity Framework 6 Getter Only 属性影响实体关系,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32481744/