如何创建实体框架外键关系? [英] How to create foreign key relationships with the Entity Framework?

查看:110
本文介绍了如何创建实体框架外键关系?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想在有一对夫妇外键关系的表建立在我的数据库一个​​新行,我一直没能得到什么顺序,什么叫需要作出一个句柄。这是我到目前为止有:

I want to create a new row in my database on a table that has a couple of foreign key relationships and I haven't been able to get a handle on what order and what calls need to be made. This is what I have so far:

db.Models.Order order = DB.Models.Order.CreateOrder( apple );
order.CustomerReference.Attach( ( from c in db.Customer where c.Id == custId select c ).First() );
db.SaveChanges();

在code未能在第二行有,他说:

The code is failing on the second line there, saying:

附加是不是有效的操作时,
  与此相关联的源对象
  相关到底是在添加,删除,
  或分离的状态。加载的对象
  使用NoTracking合并选项都
  永远分离。

Attach is not a valid operation when the source object associated with this related end is in an added, deleted, or detached state. Objects loaded using the NoTracking merge option are always detached.

任何想法?

推荐答案

(感谢约翰语法修复)

所以我想通了。这是你必须做的:

So I figured it out. This is what you have to do:

db.Models.Order order = DB.Models.Order.CreateOrder( apple );
order.Customer = (from c in db.Customer where c.Id == custId select c).First();
db.SaveChanges();

我希望帮助的人。

I hope that helps people.

这篇关于如何创建实体框架外键关系?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆