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? IsMainSubproperty in mySubclass and also create a unique key constraint forMasterIdandIsMainSubin mySubclass. This would ensure that aMasterrecord cannot have 2 mainSubrecords.UPDATE - I know this doesn't look perfect, the
IsMainSubproperty would only allow the valuestrueandnullsince setting the valuefalsewould trigger the unique constraint violation. This is logic you can add to your property setter to take anyfalsevalue and convert it to null.For what I can recall, you can create a unique key constraint that allows
nullvalue for some columns without violating the constraint. I would double check this.