Litsher - Nathan
Litsher - Nathan

Reputation: 275

Optional One to many relationship

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: : 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'.

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?

Upvotes: 0

Views: 922

Answers (1)

strickt01
strickt01

Reputation: 4048

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.

Upvotes: 1

Related Questions