TLDR - 我是否可以使用仅识别一对多关系的实体框架创建单独的表?很多方面都不了解一方。
我有一个Polygon类,以简单的形式出现在这里:
public class Polygon
{
List<LineSegment> _lineSegments = new List<LineSegment>();
public List<LineSegment> LineSegments
{
get { return _lineSegments; }
protected set { _lineSegments = value; }
}
// ...
}
LineSegment
类,它没有多边形的自然引用,我也不想仅为EF添加一个:
public class LineSegment
{
public virtual Distance Magnitude
{
get { return _magnitude; }
set { _magnitude = value; }
}
private Distance _magnitude;
public virtual Point BasePoint
{
get { return _basePoint; }
set { this._basePoint = value; }
}
private Point _basePoint;
public virtual Direction Direction
{
get { return _direction; }
set { _direction = value; }
}
private Direction _direction;
// ...
}
所以这里有一对多的关系。根据规范化原则,这应该使用一个单独的表来处理,该表将Polygon ID与LineSegment ID相关联。但是,当我使用Fluent API映射以下内容时,
modelBuilder.Entity<Polygon>()
.HasMany(polygon => polygon.LineSegments);
EF期望LineSegments表中的Polygon_DatabaseId。这不会是EF第一次破坏正常化。但我可以将其设置为多对多关系,这将创建第三个表:
modelBuilder.Entity<Polygon>()
.HasMany(polygon => polygon.LineSegments)
.WithMany();
我可以将内容插入此表中。但是,当我尝试将它们取出并返回到Polygon对象时,不会加载LineSegments。这是查询代码:
private static List<Expression<Func<Polygon, object>>> polygonRegionNaviationProperties = new List<Expression<Func<Polygon, object>>>()
{
(polygon => polygon.LineSegments.Select(lineSegment => lineSegment.Magnitude)),
(polygon => polygon.LineSegments.Select(lineSegment => lineSegment.BasePoint.X)),
(polygon => polygon.LineSegments.Select(lineSegment => lineSegment.BasePoint.Y)),
(polygon => polygon.LineSegments.Select(lineSegment => lineSegment.BasePoint.Z))
};
public Polygon GetPolygon(int? databaseId)
{
if(databaseId != null)
{
Polygon retrievedPolygon = Query((polygon => polygon.DatabaseId == databaseId), polygonRegionNaviationProperties);
return retrievedPolygon;
}
else
{
return null;
}
}
通用查询方法:
public virtual T Query(Expression<Func<T, bool>> match, List<Expression<Func<T, object>>> includes = null)
{
using (var databaseContext = new ClearspanDatabaseContext())
{
databaseContext.Database.Log = Console.Write;
if (includes != null)
{
var dataSet = databaseContext.Set<T>(); // Get the relevant DataSet
T retrievedObject = includes.Aggregate( // Eagerly load the passed navigation properties
dataSet.AsQueryable(),
(current, include) => current.Include(include)
).SingleOrDefault(match);
return retrievedObject;
}
else
{
T retrievedObject = databaseContext.Set<T>().SingleOrDefault(match);
return retrievedObject;
}
}
}
那么有可能对这种关系建模,以便我们将一对多表与多边形和LineSegments表分开吗?如果是这样,我如何使用Fluent API执行此操作?提前致谢。