c# - Code-first 1..n mapping error -


i have these 2 models:

public class product {     public int id {get; set;}     public int productgroupid {get; set;} }  public class productgroup {     public int id {get; set;}     public virtual icollection<product> products {get; set;} } 

and mappings:

public class productmap {     this.totable("products");      this.haskey(t => t.id).property(t => t.id).hascolumnname("id")         .hasdatabasegeneratedoption(databasegeneratedoption.identity);      this.property(t => t.key).hascolumnname("id_product_group")         .isrequired(); }  public class productgroupmap { {     this.totable("product_groups");      this.haskey(t => t.id).property(t => t.id).hascolumnname("id")         .hasdatabasegeneratedoption(databasegeneratedoption.identity);      this.hasoptional(t => t.products)         .withmany()         .willcascadeondelete(); } 

the code compiles when start app, following exception:

invalid column "products_id"

is mapping incorrect?

your foreign key mapping incorrect. replace hasoptional code in productgroupmap with:

hasmany(_ => _.products)     .withrequired()     .hasforeignkey(_ => _.productgroupid); 

this should read "productgroup has collection of products, product must belong productgroup, , relation controlled foreign key property product.productgroupid".

hasoptional/hasrequired intended use entities, having required/optional reference navigation property (e.g., product.countryoforigin), not collection navigation property.

in other words, 1-* association between entities configured both sides: either principal entity (productgroup in case), or dependent entity (product).

use hasmany, when configuring side of principal entity.
use hasoptional/hasrequired, when configuring side of dependent entity:

  • hasoptional when reference principal entity optional;
  • hasrequired - when reference required.

Comments

Popular posts from this blog

javascript - Any ideas when Firefox is likely to implement lengthAdjust and textLength? -

matlab - "Contour not rendered for non-finite ZData" -

delphi - Indy UDP Read Contents of Adata -