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 ?
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 mySub
class and also create a unique key constraint forMasterId
andIsMainSub
in mySub
class. This would ensure that aMaster
record cannot have 2 mainSub
records.UPDATE - I know this doesn't look perfect, the
IsMainSub
property would only allow the valuestrue
andnull
since setting the valuefalse
would trigger the unique constraint violation. This is logic you can add to your property setter to take anyfalse
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.