I know a lot of people is asking about one-to-one relationships on EF 4.1 but I can't seem to find an answer for this problem.
I have these POCO classes:
public class Contact
{
public decimal nCont_id { get; set; }
public virtual WebsiteMembership WebsiteMembership { get; set; }
//a bunch of other properties
}
public class WebsiteMembership
{
public int WebsiteMembershipId { get; set; }
public virtual Contact Contact { get; set; }
}
Website membership's primary key (WebsiteMembershipId) is also a foreign key that references Contact's nCont_id.
I'm trying to set this up using the fluent API:
protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
//This is being done because of the unconventional column names I have to live with
modelBuilder.Conventions.Remove<NavigationPropertyNameForeignKeyDiscoveryConvention>();
//bunch of other stuff
modelBuilder.Entity<Contact>().ToTable("contacts");
modelBuilder.Entity<Contact>().HasKey(b => b.nCont_id);
modelBuilder.Entity<Contact>().HasOptional(b => b.WebsiteMembership).WithRequired(b => b.Contact).Map(b => b.MapKey("WebsiteMembershipId"));
modelBuilder.Entity<WebsiteMembership>().ToTable("WebsiteMembership");
modelBuilder.Entity<WebsiteMembership>().HasKey(b => b.WebsiteMembershipId);
}
But I get an exception when I try doing:
var websiteMembership = context.WebsiteMemberships.Where(c => c.WebsiteMembershipId == 1645942).FirstOrDefault();
Exception:
Schema specified is not valid. Errors: (263,6) : error 0019: Each property name in a type must be unique. Property name 'WebsiteMembershipId' was already defined.
Does this mean I can't set the same primary key as a foreign key on EF CodeFirst? Or I'm doing something wrong here? Would it work if the primary key wasn't the same column as the foreign key?
Advice is very much appreciated!
int
and notdecimal
EF was looking for a field Contact_nCont_id. I then used your piece of code and made the propertydecimal
and everything worked beautifully. – Salesmanship