我遇到了一个概念上的障碍:实体框架是如何推断实体关系的。所以,虽然我已经解决了我的问题,但对我来说,它的工作原理是毫无意义的。
我有以下实体,在这里,以简化的形式,来自几何类库。
类,其中隐藏主/外键属性以保持简洁性,并将重点放在以下问题上:
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;
}向量类,它是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类是向量的一个子类,它还隐藏了主/外键属性:
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的唯一属性,只将属性映射为getter和setter。但是,为了避免获得
无法确定从属操作的有效排序。依赖项可能由于外键约束、模型需求或存储生成的值而存在。
在将一个LineSegment插入数据库(行和向量工作得很好)时,我必须在我的模型创建中有以下内容:
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);
}其中大部分内容对我来说都是有意义的,但是对于实体框架来说,要理解我的模型而不产生上面引用的错误,为什么我必须包括最后一条语句呢?
发布于 2015-09-10 18:18:20
实体框架似乎自动忽略类型字符串、基元类型和枚举类型的纯getter属性。在所有其他情况下,您必须使用.Ignore()方法或[NotMapped]注释显式忽略它们。
https://stackoverflow.com/questions/32481744
复制相似问题