简体   繁体   中英

No data for table with 2 foreign keys to one table EF 6

ASP.NET. EF 6.0.2, MVC 5.1.1. I have a table with 2 foreign keys to the same table.

public class order
{
public int orderID {get;set;}
public int deliveryplaceID {get;set;}
public int invoiceplaceID {get;set;}

public virtual Place Deliveryplace {get;set;}
public virtual Place Invoiceplace {get;set;}
}

Saving of the object works fine, and the deliverplaceID and invoiceplaceID in the database-table were filled. Now, when I try to show the data:

public ActionResult Index()
{
var orderdata = db.order.Include(d => d.Deliveryplace).Include(i => i.Invoiceplace);
return View(orderdata.ToList());
}

In the view:

@Html.DisplayFor(modelItem => item.Deliveryplace.Zip)
@Html.DisplayFor(modelItem => item.Invoiceplace.Zip)

It does not show any data for this two fields. Other fields are shown, also other fields of other foreign tables. Any ideas?

Solved. Thanks for your tip JC. You put me on the right way.

Solution was
1) Define the foreignkey in order table

public class order
{
public int orderID {get;set;}
public int deliveryplaceID {get;set;}
public int invoiceplaceID {get;set;}

[ForeignKey("deliveryplaceID")]
public virtual Place Deliveryplace {get;set;}
[ForeignKey("invoiceplaceID")]
public virtual Place Invoiceplace {get;set;}
}

2) Define in modelContext:

protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
modelBuilder.Entity<order>()
.HasRequired(c => c.Deliveryplace)
.WithMany()
.WillCascadeOnDelete(false);

modelBuilder.Entity<order>()
.HasRequired(c => c.Invoiceplace)
.WithMany()
.WillCascadeOnDelete(false);
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM