简体   繁体   English

防止在实体框架中保存子对象

[英]Prevent saving of child objects in Entity Framework

Using Entity Framework and having the following class: 使用实体框架并具有以下类:

public class TestClass{

    [Key]
    public int id {get; set;}
    public int foreignId {get; set;}

    [ForeignKey("foreignId")
    public MyObject myObject {get; set;}
}

With this class I want to save the "TestClass" but the entity framework first tries to save/create the "myObject" that doesn't need to get saved because it's only a reference. 对于此类,我想保存“ TestClass”,但是实体框架首先尝试保存/创建不需要保存的“ myObject”,因为它只是一个引用。 In some forums ( enter link description here ) I read that I has to set the myObject explicitely to "null" before saving, but in my opinition this is quite annoying. 在某些论坛(请在此处输入链接描述 )中,我读到我必须在保存之前将myObject显式设置为“ null”,但是在我看来,这很烦人。

So I want to ask if there is any annotation or something like "IgnoreOnSave" that I can add to the myObject? 因此,我想问是否可以添加到myObject的注释或诸如“ IgnoreOnSave”之类的东西?

[ForeignKey("foreignId", "ignoreOnSave")]
public MyObject myObject {get; set;}

Update 更新资料

[NotMapped] did it for me: [NotMapped]为我做了:

[NotMapped]
[ForeignKey("foreignId")]
public MyObject myObject {get; set;}

With this attribute I can load the object with the foreign sub object, but on saving the subObject "myObject" is ignored. 使用此属性,我可以使用外部子对象加载该对象,但是在保存子对象时,“ myObject”将被忽略。 I only need to assure in code, that the ID of "myObject" is copied to the foreign-key-property of the main object. 我只需要在代码中确保将“ myObject”的ID复制到主对象的外键属性。

Additionally (I'm creating a Web-Api-Solution) I added a [JsonIgnore] to the foreign-key-property so that I have clean interfaces. 另外(我正在创建一个Web-Api-Solution)我在外键属性中添加了一个[JsonIgnore] ,以便拥有干净的界面。

Update 更新资料

Using [NotMapped] leads to that the linq expression ".include" can't be used for the respective properties anymore. 使用[NotMapped]导致linq表达式“ .include”不再可用于相应的属性。

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

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