How do I map a 0..1 to * relation in EF 4.0 FluentAPI CTP5? I keep geting this error
Because all of the properties in the Dependent Role are non-nullable, multiplicity of the Principal Role must be '1'.
And I do not know how exactly to fix it..
My code looks like this
public class Child{
public int pID { get; set; }
public Parent Parent_Object{ get; set; }
public int Parent{ get; set; }
public Child() {
}
}
public class Parent {
public int pID { get; set; }
public List<Child> Children { get; set; }
public Parent () {
}
}
For mapping the code looks lik开发者_如何学编程e this
modelBuilder.Entity<Child>().HasKey(c=> c.pID);
modelBuilder.Entity<Parent>().HasKey(c=> c.pID);
modelBuilder.Entity<Child>().HasOptional(c=> c.Parent_Object)
.WithMany(p => p.Children)
.HasForeignKey(p => p.Parent);
Also is it possible to have only
public Parent Parent{ get; set; }
instead of
public Parent Parent_Object{ get; set; }
public int Parent{ get; set; }
In the database the FKfield is named "Parent" not "ParentpID". In this case how should the mapping look like?
You can simply remove Foreign Key Column from the mapping and everything will work fine:
public class Child{
public int pID { get; set; }
public Parent Parent_Object{ get; set; }
public Child() { }
}
public class Parent {
public int pID { get; set; }
public List Children { get; set; }
public Parent () { }
}
public class Context : DbContext {
protected override void OnModelCreating(System.Data.Entity.ModelConfiguration.ModelBuilder modelBuilder) {
modelBuilder.Entity().HasKey(c => c.pID);
modelBuilder.Entity().HasKey(c => c.pID);
modelBuilder.Entity().HasOptional(c => c.Parent_Object).WithMany(p => p.Children);
}
public DbSet Parents { get; set; }
public DbSet Childs { get; set; }
}
As an alternative, you can use the nullable int Parent property, like this:
public int? ParentId { get; set; }
In this case your initial code will be correct as well.
精彩评论