简体   繁体   中英

Entity Framework - How to return single entity without related objects

Im using EF6, DB First, in a MVC project with LazyLoading turned off . However upon updating some of the entities properties, I found that upon updating an entities related objects in a function in the same context, that by the time I return the single entity, it also contains the related objects that I had updated. I would like to return the single entity only.

So my question is, is there a better way to "clean off" the related entities other than creating a new context and retrieving the entity again? Or would you update the related entities in a different context? Or is there a cleaner method than these?

Thanks in advance!

Your issue is that you are expecting Entity Framework to behave in a way that it is not intended to do. Based on your comments and question, it seems that in the same context you are touching a parent entity and one or more of its children entities. As a result, the change tracker is putting all of that together for you.

Your second issue is that your code return probably looks something like this:

public ActionResult Stuff(){
    //MyEntityFrameworkClass is an autogenerated Entity Framework 
    //object that represents a table in your database
    List<MyEntityFrameworkClass> items = db.MyEntityFrameworkClass.ToList();
    Return Json(items);
}

This is bad because you are returning everything in the database for each of these items including any of the related entities that have been attached. What happens in these instances:

  • You don't need to return every single column
  • You want to return some auto calculated columns not included in the entity
  • You need values from multiple entities

This is where View Models (or Data Transfer Objects) come into play. Create a model specifying EXACTLY what your client needs and nothing more.

public class MyApiModel(){
   public string Name {get;set;}

   public int SomethingElse {get;set;}

   //Computed property in our view model
   //Lets say anything greater than 2 is valid
   public bool IsValid => SomethingElse > 2;
}

Now you should return a List (or whatever) of this type of object.

public ActionResult Stuff(){
    List<MyApiModel> items = db.MyEntityFrameworkClass.Select(x=>new MyApiModel{
          //Notice I am not setting the isvalid property
          //Its computed, class takes care of returning proper value
          Name = x.MyNameColumn, 
          SomethingElse = x.MyOtherColumn
    }.ToList();
    Return Json(items);
}

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