可选一对多的关系 [英] Optional One to many relationship
问题描述
我试图让使用流利的API可选的一对多的关系。但它似乎并不像我得到这个错误的工作:
I am trying to make and optional one to many relationship using fluent API. But it doesn't seem to work as I get this error:
InBuildingNavigator.Data.Models.ConnectionPointRoute_Segment:与作用ConnectionPointRoute_Segment引用约束ConnectionPointRoute_Segment_Target关系中的多重冲突。因为所有的从属角色的属性是不可为空,校长角色的多重性必须是'1'。
InBuildingNavigator.Data.Models.ConnectionPointRoute_Segment: : Multiplicity conflicts with the referential constraint in Role 'ConnectionPointRoute_Segment_Target' in relationship 'ConnectionPointRoute_Segment'. Because all of the properties in the Dependent Role are non-nullable, multiplicity of the Principal Role must be '1'.
这是modelcreation:
This is the modelcreation :
protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
base.OnModelCreating(modelBuilder);
modelBuilder.Entity<ConnectionPointRoute>()
.HasKey(c => new {c.ConnectionPointId, c.RouteId, c.SegmentId});
modelBuilder.Entity<ConnectionPoint>()
.HasMany(c => c.ConnectionPointRoutes)
.WithRequired(x => x.ConnectionPoint)
.HasForeignKey(c => c.ConnectionPointId);
modelBuilder.Entity<Route>()
.HasMany(c => c.ConnectionPointRoutes)
.WithRequired(x => x.Route)
.HasForeignKey(c => c.RouteId);
modelBuilder.Entity<Segment>()
.HasMany(c => c.ConnectionPointRoutes)
.WithOptional(s => s.Segment)
.HasForeignKey(s => s.SegmentId);
}
和是这种模型
public class ConnectionPointRoute
{
public int ConnectionPointId { get; set; }
public int RouteId { get; set; }
public int? SegmentId { get; set; }
public int Position { get; set; }
public ConnectionPoint ConnectionPoint { get; set; }
public Route Route { get; set; }
public Segment Segment { get; set; }
}
public class Segment
{
public Segment()
{
ConnectionPointRoutes = new List<ConnectionPointRoute>();
}
public int SegmentId { get; set; }
public int ConnectionPointIdEnd { get; set; }
public string ConnectionName { get; set; }
public string ConnectionInformation { get; set; }
public string Image { get; set; }
public string Direction { get; set; }
public ICollection<ConnectionPointRoute> ConnectionPointRoutes { get; set; }
}
有什么想法?
推荐答案
这是因为你正试图确定对 ConnectionPointRoute
复合主键,包括 SegmentId
这可为空。你不能定义一个空的列主键。
It's because you are trying to define a composite primary key on ConnectionPointRoute
that includes SegmentId
which is nullable. You cannot define a primary key on a nullable column.
这篇关于可选一对多的关系的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!