4

Most questions I have found were not the type I am 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 User can exists without being a Customer and a Customer can exist without being an User.

I tried the fluent API like this:

modelBuilder.Entity<Customer>()
    .HasOptional<User>(c => c.User)
    .WithOptionalDependent(c => c.Customer)
    .Map(c => c.MapKey("UserId"));

But it keeps giving me this error when I try to create the 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 the fluent 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 the column in the model instead of having to use MapKey?

Roger Far
  • 2,178
  • 3
  • 36
  • 67

1 Answers1

2

See link 1

And link 2 too

The problem with that links is I'm not sure if they provide a actual solution to the problem: because I don't know if it provide uniqueness for the foreign key in both tables (as this link suggest). Because that, not having EF unique constraints, you have to create it manually (in the generator)

And finally link explains that the unique form of performing an 1:* relationship is using the foreign key of one of the tables as primary key of the other.

Good luck.

Community
  • 1
  • 1
rlartiga
  • 429
  • 5
  • 21
  • 1
    Thanks the 2nd link pointed me in the right direction, do you perhaps have an answer on my edit? – Roger Far Jan 14 '14 at 04:24
  • I read it yeah. I think it's more a culprit in the EF implementation. I created the tables model first and then generated code first from that. EF actually made it an 1..* relation instead of a 1..1 relation. – Roger Far Jan 15 '14 at 05:09