Freshblood
Freshblood

Reputation: 6431

More than one one-to-one relationship on a entity

You see my model structure on Entity Framework 5.0 and User entity hold reference to Address and Address1 entities. In the other side, Address hold Users collection as reference but Entity framework couldn't know that Users dependendant on which Address reference So i got exception.

What are solutions exist for it ? I mean fluent and none-fluent solutions please.

public class User
{
    public int Id { get; set; }

    public Address Address { get; set; }

    public Address Address1 { get; set; }
}

public class Address
{
    public int Id { get; set; }

    public ICollection<User> Users { get; set; }
}

Upvotes: 0

Views: 81

Answers (1)

Rui Jarimba
Rui Jarimba

Reputation: 17894

First step is to include the foreign keys in User class:

public class User
{
    public int Id { get; set; }
    public int AddressId { get; set; }
    public int Address1Id { get; set; }

    public Address Address { get; set; }

    public Address Address1 { get; set; }
}

Fluent API mapping:

modelBuilder.Entity<User>()
            .HasRequired(a => a.Address)
            .WithMany()
            .HasForeignKey(u => u.AddressId);

modelBuilder.Entity<User>()
            .HasRequired(a => a.Address1)
            .WithMany()
            .HasForeignKey(u => u.Address1Id);

More details here:

http://weblogs.asp.net/manavi/archive/2011/05/01/associations-in-ef-4-1-code-first-part-5-one-to-one-foreign-key-associations.aspx

Upvotes: 1

Related Questions