Search code examples
databaseentity-frameworkmappingrelationshipsfluent-entity-framework

Entity Framework : how to create double relationship (1-1 and many-1) with same objects


I have two class :

class Sub
{
    public Guid Id { get; set; }
    public DateTime ValidDate { get; set; }
    public Guid MasterId { get; set; }
    public Master Master { get; set; }
}

and

class Master
{
    public Guid Id { get; set; }
    public int Data { get; set; }

    public ICollection<Sub> Subs { get; set; }
    public Sub MainSub { get; set; }
}

To be simple, a master have a main sub to define it, and can have 0 or more "secondary" subs. I've tried to do mapping this way

var mBuilder = modelBuilder.Entity<Master>();
mBuilder.HasMany(m => m.Subs).WithOne(m => m.Master).HasForeignKey(m => m.MasterId);
mBuilder.HasOne(m => m.MainSub).WithOne(m => m.Master);

but I have an exception as expected ("Master cannot participate in two relationships"). I don't want to change my model cause it fits what I need, how can I perform such a mapping to do so ?


Solution

  • You cannot map this relationship. Every relationship has 2 endpoints and one complex property in your class cannot be the endpoint for 2 relationships.

    I would create a bool? IsMainSub property in my Sub class and also create a unique key constraint for MasterId and IsMainSub in my Sub class. This would ensure that a Master record cannot have 2 main Sub records.

    UPDATE - I know this doesn't look perfect, the IsMainSub property would only allow the values true and null since setting the value false would trigger the unique constraint violation. This is logic you can add to your property setter to take any false value and convert it to null.

    For what I can recall, you can create a unique key constraint that allows null value for some columns without violating the constraint. I would double check this.