简体   繁体   English

可选一对多关系

[英]Optional One to many relationship

I am trying to make and optional one to many relationship using fluent API. 我正在尝试使用流利的API进行可选的一对多关系。 But it doesn't seem to work as I get this error: 但是由于出现此错误,它似乎不起作用:

InBuildingNavigator.Data.Models.ConnectionPointRoute_Segment: : Multiplicity conflicts with the referential constraint in Role 'ConnectionPointRoute_Segment_Target' in relationship 'ConnectionPointRoute_Segment'. InBuildingNavigator.Data.Models.ConnectionPointRoute_Segment::多重性与关系“ ConnectionPointRoute_Segment”中的角色“ ConnectionPointRoute_Segment_Target”中的引用约束冲突。 Because all of the properties in the Dependent Role are non-nullable, multiplicity of the Principal Role must be '1'. 因为从属角色中的所有属性都是不可为空的,所以主体角色的多重性必须为'1'。

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);
    }

and this is the model : 这是模型:

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; }
}

Any thoughts? 有什么想法吗?

It's because you are trying to define a composite primary key on ConnectionPointRoute that includes SegmentId which is nullable. 这是因为您试图在ConnectionPointRoute上定义一个包含可以为空的SegmentId的组合主键。 You cannot define a primary key on a nullable column. 您不能在可为空的列上定义主键。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM