1

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. 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.

So I want to ask if there is any annotation or something like "IgnoreOnSave" that I can add to the myObject?

[ForeignKey("foreignId", "ignoreOnSave")]
public MyObject myObject {get; set;}
SNO
  • 793
  • 1
  • 10
  • 30
  • 2
    You can use the `[NotMapped]` attribute to tell entity framework to not worry about it. But in my opinion that reference shouldn't be contained in a database model, but rather a separate (view) model. – nbokmans Jul 25 '18 at 13:49
  • @nbokmans Thank you for that hint. This seems to be a very good solution for me. Could you explain your opinion that reference shouldn't be contained in a database model? – SNO Jul 25 '18 at 13:59
  • Well, mainly for the simple reason that a database model should (in my opinion) be no more than that - a model of the database entity. – nbokmans Jul 25 '18 at 16:57
  • unfortunately the ```[NotMapped]``` doesn't work when you also/still want to use the linq expression "includes...". :( – SNO Jul 26 '18 at 09:42

1 Answers1

0

Update

[NotMapped] did it for me:

[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. I only need to assure in code, that the ID of "myObject" is copied to the foreign-key-property of the main object.

Additionally (I'm creating a Web-Api-Solution) I added a [JsonIgnore] to the foreign-key-property so that I have clean interfaces.

Update

Using [NotMapped]leads to that the linq expression ".include" can't be used for the respective properties anymore.

SNO
  • 793
  • 1
  • 10
  • 30