简体   繁体   中英

Entity Framework 4.4 SaveChanges Exclude Related Entity

I'm using EntityFramework.dll version 4.4 with .NET 4.0. I have an entity that's contains a reference to another entity like the following:

[Table("Bar")]
public class Bar
{
  public string Id { get; set; }
  public Foo Foo { get; set; }
  [ForeignKey("Foo")]
  public string FooId {get; set; }
}

When I want to add a new "Bar" record to the database, EntityFramework tries to also add an instance of "Foo", but I don't want it to do this. Is there a way to tell EF to ignore the Foo entity when Bar is created? I do not want to set [NotMapped] on Foo because it does need to be mapped - it's just that I don't want it to save. So I'd like for the following to work:

public void CreateBar(Bar b)
{
   _barContext.Bars.Add(b);
   // This function doesn't exist, but I would like it to exist
   _barContext.Exclude("Foo");
   _barContext.SaveChanges();
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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