简体   繁体   English

实体框架:插入与另一个实体关联的新实体

[英]Entity Framework: Inserting new entity associated with another entity

I have two tables FilesystemEntries and CacheEntries where there is an association of 0..1 CacheEntry per FilesystemEntry (that is a FilesystemEntry can have a null CacheEntry, but not vice-versa). 我有两个表FilesystemEntries和CacheEntries,其中每个FilesystemEntry的关联为0..1 CacheEntry(即FilesystemEntry的CacheEntry可以为空,反之亦然)。 Initially, the CacheEntry for all FilesystemEntries is null. 最初,所有FilesystemEntries的CacheEntry为null。 I'm having trouble changing this (adding a new CacheEntry). 我在更改此设置(添加新的CacheEntry)时遇到麻烦。 The code (truncated) looks like this: 代码(被截断)如下所示:

FilesystemEntry filesystemEntry; // Already exists in database
CacheEntry cacheEntry;           // A new one is created
// ...
filesystemEntry.CacheEntry = cacheEntry;       // Was null before (verified in debugger)
cacheEntry.FilesystemEntry = filesystemEntry;
_db.AddToCacheEntries(cacheEntry);

However, I'm recieving the following error: 但是,我收到以下错误:

System.Data.UpdateException: A relationship is being added or deleted from an 
AssociationSet 'FK_CacheEntries_0'. With cardinality constraints, a corresponding 
'CacheEntries' must also be added or deleted.

Any entity framework wizards know what's going on? 任何实体框架向导都知道发生了什么事?

Similarly, is there any way to allow the database to handle the "ON DELETE CASCADE" (I'm using sqlite, so it'll be via a trigger)? 同样,是否有任何方法允许数据库处理“ ON DELETE CASCADE”(我使用的是sqlite,因此将通过触发器)? This would be a lot more convenient and future-proof than specifying all the deletes in the DAL. 与在DAL中指定所有删除操作相比,这将更加方便且具有前瞻性。

Not sure if this is the problem. 不知道这是否是问题。

But I'd try doing this: 但我会尝试这样做:

FilesystemEntry filesystemEntry; // Already exists in database
CacheEntry cacheEntry;   // A new one is created        
filesystemEntry.CacheEntry = cacheEntry; 
// redundant cacheEntry.FilesystemEntry = filesystemEntry;
// redundant _db.AddToCacheEntries(cacheEntry);
_db.SaveChanges();

The first redundant operation might be causing the problem. 第一次冗余操作可能会导致问题。

As for cascade delete take a look at this Tip for an explanation of how Cascade delete really works in EF. 至于级联删除,请查看此技巧以解释级联删除在EF中如何真正起作用。

Alex 亚历克斯

I may be wrong, but unless I'm misunderstanding your entity relationships, you might try it without the 我可能是错的,但是除非我误解了您的实体关系,否则您可能会尝试不使用

cacheEntry.FilesystemEntry = filesystemEntry;

line. 线。 This should be implicit by the fact that you set 您设置的事实应该隐含了这一点

filesystemEntry.CacheEntry = cacheEntry;

Also I've had good luck using the following type of assignment when dealing with navigation properties: 另外,在处理导航属性时,我也很高兴使用以下类型的分配:

cacheEntry.FilesystemEntryReference.Value = filesystemEntry;

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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