c# - Invalid Column Name Error When Trying to Associate Objects with EntityFramework -


the entity framework giving me trouble.

here tables:

products

products table

related products

relatedproducts table

and db context (part of it, anyway)...

applicationcontext.cs

public class applicationcontext : dbcontext {         public applicationcontext() : base("defaultconnection")         {         }          public dbset<product> products { get; set; }         public dbset<relatedproduct> relatedproducts { get; set; } } 

and models...

product.cs

public class product {     public int id              { get; set; }     public string manufacturer { get; set; }     public string model        { get; set; }     public string partnumber   { get; set; }     public int categoryid      { get; set; }     public string description  { get; set; }     public decimal price { get; set; }      public virtual icollection<relatedproduct> relatedproducts { get; set; } } 

relatedproduct.cs

public class relatedproduct {     public int id        { get; set; }     public int ownerid   { get; set; }     public int productid { get; set; }      public virtual product owner { get; set; }     public virtual product product { get; set; } } 

what trying do

loop through list of related products this:

<ul class="activity">       @foreach (var related in @model.relatedproducts)       {              <li>                   <i class="fa fa-chevron-right red"></i> <strong>@related.product.manufacturer:</strong> @related.product.model              </li>       } </ul> 

the problem

i keep getting errorl

{"invalid column name 'product_id'.\r\ninvalid column name 'product_id'.\r\ninvalid column name 'product_id'."} 

any ideas?

you must tell ef if product.relatedproducts inverse navigation property of relatedproduct.owner or of relatedproduct.product. both possible , valid , ef can't decide on own.

solution data annotations (assuming owner inverse of relatedproducts):

[inverseproperty("relatedproducts")] public virtual product owner { get; set; }  public virtual product product { get; set; } 

or fluent api:

modelbuilder.entity<relatedproduct>()     .hasrequired(r => r.owner)     .withmany(p => p.relatedproducts)     .hasforeignkey(r => r.ownerid);  modelbuilder.entity<relatedproduct>()     .hasrequired(r => r.product)     .withmany()     .hasforeignkey(r => r.productid)     .willcascadeondelete(false); 

probably fluent api solution work because need disable cascading delete 1 of relationships isn't possible data annotations.


Comments

Popular posts from this blog

javascript - RequestAnimationFrame not working when exiting fullscreen switching space on Safari -

Python ctypes access violation with const pointer arguments -