1

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 ?

cdie
  • 4,014
  • 4
  • 34
  • 57

1 Answers1

1

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.

Arturo Martinez
  • 3,737
  • 1
  • 22
  • 35
  • Thanks for this answer. In fact, I would rather keep my MainSub a pure in memory notion, extract it from collection when accessing and keep a single relationship. It's weaker cause I cannot assert, from a db perspective, that I have a mainSub defined, but it's enough ok. If I had to implement the solution, your's seems to be the proper one, so I'll mark it as answer – cdie Dec 08 '16 at 10:30