如何在EF中将外键包含到savechanges函数中 [英] How to include foreign keys into savechanges function in EF

查看:75
本文介绍了如何在EF中将外键包含到savechanges函数中的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述





我有两张桌子,一张是产品,第二张是标签。他们有各自的专栏。产品和标签之间存在一对多的关系。一个产品可以有多个标签 (这必须使用数据库,没有Javascript) 。所以,我把Product key作为外键包含在tags表中。我可以使用代码优先方法在Entity框架中创建模型结构。



问题:有两个字段用于包含来自用户的标签。一个是产品版本,另一个是标签的名称。标签的模型包含ID(生成数据库),版本,名称,产品对象集合和产品ID作为外键。



当我从表单到控制器接收数据时它停留在db.SaveChanges()。我说

Hi,

I have two tables one is product and second is tags. They have their respective columns. There is one to many relationship between product and tags. One product can have multiple tags(This has to be done using Database, no Javascript). So, I have included Product key as foreign key into tags table. I am able to create Model structure in Entity framework using code first approach.

Issue: There are two fields form for including tags from user. One is Product version and other is name of the tag. Where as tags' model contain ID(Database generated), Version, Name, Collection of product object and productID as foreign key.

When I receive data from form to controller it stuck at db.SaveChanges(). I says

The INSERT statement conflicted with the FOREIGN KEY constraint



我如何设法包含Foreign键入标签对象,以便EF保存更改?



我尝试过:



我想的是分别获取产品ID,然后将其包含在tags对象中,然后将其添加到上下文对象中以保存更改,但这是远景。有更好的方法吗?


How can I manage to include Foreign keys into tags object so that EF will save change?

What I have tried:

What I am thinking is to get the product id separately and then include it into tags object which will then add into context object for saving changes, but this is long shot. Is there is better way to do this?

推荐答案

听起来你实际上有很多关系。这需要一个包含产品和标签的外键的链接表。可以无限制地插入每个产品,并且可以无限制地插入每个新标签。当你知道哪些标签应该连接到哪个产品然后你在链接表中插入一个新的关系。



如果不是这样的话那么你将不得不在插入标签之前插入每个产品。



我希望有所帮助。如果我错过了什么,请告诉我^ _ ^

Andy
It sounds like you actually have a many to many relationship. This requires a link table which contains a foreign key for both products and tags. Each product can be inserted without constraint and each 'new' tag can be inserted without constraint. when you know which tags should be hooked up to which product then you insert a new relationship into the link table.

If that is not the case then you will have to insert each product before you can insert the tags.

I hope that helps. If I've missed something then let me know ^_^
Andy


这篇关于如何在EF中将外键包含到savechanges函数中的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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