数据库双连通关系插入问题
我有两个表“植物”和“信息”。对于每个植物来说,都有很多信息,但是对于每个植物来说,都有一个 MainInformation。所以两者之间存在一对多的关系和一对一的关系。信息表具有 PlantID,植物表具有 MainInformationID。我希望两个表中的两个字段都不为空。但现在您无法将这两条记录中的任何一条插入到它们的表中,因为每条记录都要求它们的字段不为空,这意味着它们需要先创建另一条记录才能创建自己。也许这不是一个好的数据库设计,应该进行一些更改? (我是数据库和实体框架的新手)
我尝试手动插入数据库本身,但我做不到。我还使用 EntityFramework 尝试了此代码。
using (var context = new MyEntities())
{
var p = new Plant()
{
LatinName = "latinNameTest",
LocalName = "localNameTest",
CycleTime = 500
};
var i = new Information()
{
ShortDescription = "ShortDesc",
LongDescription = "LongDesc"
};
p.MainInformation = i;
i.Plant = p;
context.AddToPlants(p);
context.AddToInformation(i);
context.SaveChanges();
}
I have two tables Plants and Information. For every plant there are many information, but for each plant there is a single MainInformation. So there is a one-to-many relationship and a one-to-one relationship between the two. The Information table has a PlantID and the Plants table has a MainInformationID. I want both fields in both tables not to be nulls. But now you can't insert either of the two records into their tables because each one requires their fields not be null, meaning they need the other record to be created first in order to create themselves. Perhaps this is not a good database design and something should be changed? (I am new to databases and entity framework)
I tried inserting into the database itself manually but I cant do it. I also tried this code with EntityFramework.
using (var context = new MyEntities())
{
var p = new Plant()
{
LatinName = "latinNameTest",
LocalName = "localNameTest",
CycleTime = 500
};
var i = new Information()
{
ShortDescription = "ShortDesc",
LongDescription = "LongDesc"
};
p.MainInformation = i;
i.Plant = p;
context.AddToPlants(p);
context.AddToInformation(i);
context.SaveChanges();
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
您需要更改表以允许空值。没有其他方法可以做到这一点。
You need to change the tables to allow for null. There is no other way to do this.
您可能想了解数据库事务以及如何将它们与实体框架一起使用。您可以将两个 INSERTS 包装到单个数据库事务中,因此唯一的结果是它们都进入或都不进入。
这里是使用 EF 进行交易的链接。我没有通读它,但它似乎对它们的讨论足以让你开始。
You may want to look at database transactions and how to use them with the Entity Framework. You can wrap both INSERTS into a single db transaction so the only results are both of them go in or neither go in.
Here is a link for transactions using EF. I didn't read through it but it seems to talk about them enough to get you started.
1-1 FK 列之一
SQL Server 不允许在没有“代码”的情况下进行延迟约束检查更改”权限,因此即使包装在事务中也不起作用
听起来像 EAV 模式,它还有其他问题
One of
SQL Server does not allow deferred constraint checking without "code change" rights so even wrapping in a transaction won't work
Sounds like an EAV schema, which has other problems