Most of the questions I found were not what I was looking for.
I have 2 tables:
public class User
{
[Key, DatabaseGenerated(DatabaseGeneratedOption.Identity)]
public Guid UserId { get; set; }
public Guid? CustomerId { get; set; }
[ForeignKey("CustomerId")]
public Customer Customer { get; set; }
}
public class Customer
{
[Key, DatabaseGenerated(DatabaseGeneratedOption.Identity)]
public Guid CustomerId { get; set; }
public Guid? UserId { get; set; }
[ForeignKey("UserId")]
public User User { get; set; }
}
A Usercan exist without a Customer, and a Customercan exist without User.
I tried the free API as follows:
modelBuilder.Entity<Customer>()
.HasOptional<User>(c => c.User)
.WithOptionalDependent(c => c.Customer)
.Map(c => c.MapKey("UserId"));
But he keeps giving me this error when I try to create a migration:
Customer_User_Source: : Multiplicity is not valid in Role 'Customer_User_Source' in relationship 'Customer_User'. Because the Dependent Role properties are not the key properties, the upper bound of the multiplicity of the Dependent Role must be '*'.
Update
I changed my model to this:
public class User
{
[Key, DatabaseGenerated(DatabaseGeneratedOption.Identity)]
public Guid UserId { get; set; }
public virtual Customer Customer { get; set; }
}
public class Customer
{
[Key, DatabaseGenerated(DatabaseGeneratedOption.Identity)]
public Guid CustomerId { get; set; }
public virtual User User { get; set; }
}
With full API:
modelBuilder
.Entity<Customer>()
.HasOptional(l => l.User)
.WithOptionalPrincipal()
.Map(k => k.MapKey("CustomerId"));
modelBuilder
.Entity<User>()
.HasOptional(c => c.Customer)
.WithOptionalPrincipal()
.Map(k => k.MapKey("UserId"));
This seems to work, but is there a way to define a column in the model instead of using it MapKey?
source
share