Reputation: 6431
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
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:
Upvotes: 1