Only include what is included Entity Framework - c#

I am doing a big database call for a shopping cart. It includes many relations, all specified with the .Include() method.
Now I only want EF to include what I have specified. When I include a collection, it automatically loads the collection's relations.
So I have a ShoppingCart, the shopping cart has a collection if ShoppingCartProducts and that one has a relation back to ShoppingCart and to Product.
So I want to include product, but not the shopping cart again, so I do:
IQueryable<ShoppingCart> query = DbContext.ShoppingCarts
.Include(p => p.ShoppingCartProducts)
.Include(p => p.ShoppingCartProducts.Select(x => x.Product))
Later I execute a .FirstOrDefault() which executes the query. Debugging through this, it has also included ShoppingCart within each ShoppingCartProducts.
This sounds a bit small, but it is actually this way throughout the application. New architecture turns entity objects into models with different static methods and extensions. Eventually causing an StackoverflowException because it recursively includes it's relations.
So how do I only Include what I have included?
I've turned LazyLoadingEnabled to false, and ProxyCreationEnabled to false. And my collections/reations are not marked with virtual.
Checked these answers:
DBContext lazyloadingenabled set to true still loads related entities by default
It is true about the include on collections, but once a collection is included, that collection will load all other relations (I guess)
Entity Framework with Proxy Creation and Lazy Loading disabled is still loading child objects
Almost same question, yet not an good answer, only an explanation
EF 6 Lazy Loading Disabled but Child Record Loads Anyway
Using detached didn't help.
Edit:
As Evk mentioned, this has something to do with EF automatically filling up the blanks for already known relations. Question is now actually how to turn this off.
Edit 2:
So after an answer from Evk and my own workaround, we learn that these solutions don't solve the big picture. Let me try to explain:
These extensions and ConvertToModel methods are implemented in every repository and calling each other whenever it has a relation to it. The concept is actually great: Just convert to a model if you have the relation, if you have not, don't do anything. Yet because of this EF 'bug' I learn that all relations that are known inserted everywhere.
Here is an example where our solutions don't work. This for the case the code would call ConvertToModel for the ShoppingCart first, then the rest. But of course it could be visa-versa.
ShoppingCartRepository
public static ShoppingCartModel ConvertToModel(ShoppingCart entity)
{
if (entity == null) return null;
ShoppingCartModel model = new ShoppingCartModel
{
Coupons = entity.ShoppingCardCoupons?.SelectShoppingCouponModel(typeof(ShoppingCart)),
Products = entity.ShoppingCartProducts?.SelectShoppingCartProductModel(typeof(ShoppingCart)),
};
return model;
}
ShoppingCartProductRepository
public static IEnumerable<ShoppingCartProductModel> SelectShoppingCartProductModel(this IEnumerable<ShoppingCartProduct> source, Type objSource = null)
{
bool includeRelations = source.GetType() != typeof(DbQuery<ShoppingCartProduct>);
return source.Select(x => new ShoppingCartProductModel
{
ShoppingCart = includeRelations && objSource != typeof(ShoppingCart) ? ShoppingCartRepository.ConvertToModel(x.ShoppingCart) : null,
ShoppingCartCoupons = includeRelations && objSource != typeof(ShoppingCartCoupon) ? x.ShoppingCartCoupons?.SelectShoppingCouponModel(typeof(ShoppingCartProduct)) : null,
});
}
ShoppingCartCouponRepository
public static IEnumerable<ShoppingCartCouponModel> SelectShoppingCouponModel(this IEnumerable<ShoppingCartCoupon> source, Type objSource = null)
{
bool includeRelations = source.GetType() != typeof(DbQuery<ShoppingCartCoupon>);
return source.Select(x => new ShoppingCartCouponModel
{
ShoppingCart = includeRelations && objSource != typeof(ShoppingCart) ? ShoppingCartRepository.ConvertToModel(x.ShoppingCart) : null,
ShoppingCartProduct = includeRelations && objSource != typeof(ShoppingCartProductModel) ? ShoppingCartProductRepository.ConvertToModel(x.ShoppingCartProduct) : null
});
}
When you study it, you will see it can go from ShoppingCart to ShoppingCartProduct to ShoppingCartCoupon back to ShoppingCart.
My current workaround will be to figure out the aggregate roots and choose which one needs which one. But I rather have an elegant solution to solve this. Best would be to prevent EF from loading those known relations, or somehow figure out if a property was loaded that way (reflection?).

As stated in comments, that's default behavior of entity framework and I don't think it can be changed. Instead, you can change your code to prevent stackoverflow exceptions. How to do that nicely is very dependent on your codebase, but I'll provide one sketch. In the sketch above I use other entity names (because I always check if my code samples at least compile before posting them here):
public static partial class Ex {
public static CodeModel ConvertToModel(Code entity) {
if (entity == null) return null;
CodeModel model = new CodeModel();
var map = new Dictionary<object, object>();
map.Add(entity, model);
model.Errors = entity.Errors?.SelectShoppingCartProductModel(map);
return model;
}
public static ErrorModel[] SelectShoppingCartProductModel(this IEnumerable<Error> source, Dictionary<object, object> map = null) {
bool includeRelations = source.GetType() != typeof(DbQuery<Error>); //so it doesn't call other extensions when we are a db query (linq to sql)
return source.Select(x => new ErrorModel {
Code = includeRelations ? (map?.ContainsKey(x.Code) ?? false ? (CodeModel) map[x.Code] : ConvertToModel(x.Code)) : null,
// other such entities might be here, check the map
}).ToArray();
}
}
Another option is to store current model in thread local variable. If you call some ConvertToModel method and this thread local variable is not null - that means this method has been called recursively. Sample:
public static partial class Ex {
private static readonly ThreadLocal<CodeModel> _code = new ThreadLocal<CodeModel>();
public static CodeModel ConvertToModel(Code entity) {
if (entity == null) return null;
if (_code.Value != null)
return _code.Value;
CodeModel model = new CodeModel();
_code.Value = model;
model.Errors = entity.Errors?.SelectShoppingCartProductModel();
// other setters here
_code.Value = null;
return model;
}
public static ErrorModel[] SelectShoppingCartProductModel(this IEnumerable<Error> source) {
bool includeRelations = source.GetType() != typeof(DbQuery<Error>); //so it doesn't call other extensions when we are a db query (linq to sql)
return source.Select(x => new ErrorModel {
Code = includeRelations ? ConvertToModel(x.Code) : null,
}).ToArray();
}
}
If you implement this in all your ConvertToModel methods - there is no need to pass any parameters or change other parts of your code.

This solution checks if the source object type is not equal to the one we are calling ConvertToModel for.
public static ShoppingCartModel ConvertToModel(ShoppingCart entity)
{
if (entity == null) return null;
ShoppingCartModel model = new ShoppingCartModel
{
...
Products = entity.ShoppingCartProducts?.SelectShoppingCartProductModel(typeof(ShoppingCart)),
};
return model;
}
and the SelectShoppingCartProductModel extension:
public static partial class Ex
{
public static IEnumerable<ShoppingCartProductModel> SelectShoppingCartProductModel(this IEnumerable<ShoppingCartProduct> source, Type objSource = null)
{
bool includeRelations = source.GetType() != typeof(DbQuery<ShoppingCartProduct>);//so it doesn't call other extensions when we are a db query (linq to sql)
return source.Select(x => new ShoppingCartProductModel
{
....
ShoppingCart = includeRelations && objSource != typeof(ShoppingCart) ? ShoppingCartRepository.ConvertToModel(x.ShoppingCart) : null,
});
}
}
Yet this probably doesn't solve the entire problem. If you have another entity, let's say AdditionalCosts inside the ShoppingCart, that also has a reference to ShoppingCartProduct, it will still 'spin around'. If someone has a solution for this it would be great!
ShoppingCart -> ConvertToModel(shoppingCart) -> SelectAdditionalCostsModel -> ShoppingCartProduct -> ConvertToModel(shoppingCartProduct) -> ShoppingCart -> ConvertToModel(shoppingCart). And so on..

Related

DbContext in ResolveWith, HotChocolate GraphQL

So I just get started,
I have an entity which keeps the data from other entities not by a direct relation but with keeping the EntityId and EntityType(Enum).
When I read these records from GraphQL I expect to resolve a field with a resolver as follow,
public class AssignmentResolver
{
public object GetEntity( Assignment assignment, AppDbContext context)
{
if(assignment.EntityType == AssignmentEntityType.PERSON)
{
return context.People.FirstOrDefault(x => x.Id == assignment.EntityId);
}
// And more checks
return null;
}
}
Then I can say
public class AssignmentQueryType: ObjectType<Assignment>
{
protected override void Configure(IObjectTypeDescriptor<Assignment> descriptor)
{
descriptor.Field("entity").ResolveWith<AssignmentResolver>(x => x.GetEntity(default!, default!));
}
}
I wanna know if this is right or is there a better way...
I mean the better way would be using a document database for this but that's not an option for now.
I also maybe instead of putting the EntityType and EntityId can simply set an actual relation to those other entities but I wanna see if this current way is possible.
Well that was fast.
I found my problem. It seems that in the resolver I cannot just return an object because the schema should be clear when being read.
So from the resolver if I return a viewModel which is shared between all those entities then we are good to go.
So the GetEntity code will change to
public EntityViewModel GetEntity( Assignment assignment, [Service] AppDbContext context)
{
if(assignment.EntityType == AssignmentEntityType.PERSON)
{
var entity = context.People.FirstOrDefault(x => x.Id == assignment.EntityId);
return new EntityViewModel(entity);
}
// And more checks
return null;
}

error Removing child entity; deleted child entity is marked as Modified instead of Deleted

i've an unexpected issue trying to remove child entity from parent single database record.
After doing some tests we have replicated the problem.
Our C# code use Northwind database.
NWModel context = new NWModel();
Orders order = context.Orders.Where(w => w.OrderID == 10248).FirstOrDefault();
context.Entry(order).Collection(typeof(Order_Details).Name).Load();
order.Order_Details.RemoveAt(1);
System.Data.Entity.Infrastructure.DbChangeTracker changeset = context.ChangeTracker;
var changes = changeset.Entries().Where(x => x.State == System.Data.Entity.EntityState.Modified).ToList<Object>();
var detetions = changeset.Entries().Where(x => x.State == System.Data.Entity.EntityState.Deleted).ToList<Object>();
All works fine with original Order_Details table setup.
var deletions correctly has got deleted record.
In order to reproduce the issue, we have added on Order_Details table a new PK identity int field (OrderDetailId int identity); after doing that:
var deletions contain no record while var changes contain Order_Detail record.
EF set Orders property of Order_Detail to null and mark the record as Updated.
I've found a lot of articles regarding this issue, all of them suggests to mark Order_Detail Orders property to [Required].
I've tried to set [Required] attribute on FK entity as suggested in this post, (this article describe EFCore behaviour that is the same as EF6 behaviour) but is does not solve my issue.
Is this behaviour expected?
we would appreciate any comments or suggestions.
Thanks
AFAIK this is the correct behavior.
Indeed, you do not delete the detail. You remove it from the order details collection, that is you cut the relation between the order and the detail. As this relation is materialized by a navigation property on the detail side, then two things occur:
the collection is updated,
the navigation property is set to null.
Logically from this point if you SaveChanges you should have an exception because a detail cannot exist without an order, and you haven't yet deleted the detail, only cut the relation. So you should ctx.Set<orderDetail>().Remove(detail). (a bit annoying)
This is why in this case, I usually use composit key for details: detailId + orderId.
So when you remove the detail, the orderId is set to null <=> the PK is considered as null => the entity is marked for deletion.
Following tschmit007 suggestion, finally we have implemented this workaround.
On Orders entity we have used ObservableListSource<> instead of ICollection<>; into ObservableListSource<> class, void RemoveItem override method, we could manage ctx.Set<orderDetail>().Remove(detail) method.
In this way all child record deletion works as expected.
Here is implemented code:
public partial class Orders
{
public Orders()
{
Order_Details = new ObservableListSource<Order_Details>();
}
[Key]
public int OrderID { get; set; }
……………
public virtual ObservableListSource<Order_Details> Order_Details { get; set; }
}
public class ObservableListSource<T> : ObservableCollection<T>, IListSource
where T : class
{
private IBindingList _bindingList;
bool IListSource.ContainsListCollection { get { return false; } }
IList IListSource.GetList()
{
return _bindingList ?? (_bindingList = this.ToBindingList());
}
private bool _bRemoveInProgress = false;
protected override void RemoveItem(int index)
{
if (!_bRemoveInProgress && index>=0)
{
_bRemoveInProgress = true;
DbContext cntx = this[index].GetDbContextFromEntity();
Type tp = this[index].GetDynamicProxiesType();
cntx.Set(tp).Remove(this[index]);
base.RemoveItem(index);
}
_bRemoveInProgress = false;
}
}
public static class DbContextExtender
{
public static Type GetDynamicProxiesType(this object entity)
{
var thisType = entity.GetType();
if (thisType.Namespace == "System.Data.Entity.DynamicProxies")
return thisType.BaseType;
return thisType;
}
public static DbContext GetDbContextFromEntity(this object entity)
{
var object_context = GetObjectContextFromEntity(entity);
if (object_context == null)
return null;
return new DbContext(object_context, dbContextOwnsObjectContext: false);
//return object_context;
}
private static ObjectContext GetObjectContextFromEntity(object entity)
{
var field = entity.GetType().GetField("_entityWrapper");
if (field == null)
return null;
var wrapper = field.GetValue(entity);
var property = wrapper.GetType().GetProperty("Context");
var context = (ObjectContext)property.GetValue(wrapper, null);
return context;
}
}

Get DbContext from Entity in Entity Framework Core

Is there a way to get an instance of the DbContext an entity is being tracked by (if any)?
I found the following suggestion/solution for EF6
Get DbContext from Entity in Entity Framework
public static DbContext GetDbContextFromEntity(object entity)
{
var object_context = GetObjectContextFromEntity( entity );
if ( object_context == null )
return null;
return new DbContext( object_context, dbContextOwnsObjectContext: false );
}
private static ObjectContext GetObjectContextFromEntity(object entity)
{
var field = entity.GetType().GetField("_entityWrapper");
if ( field == null )
return null;
var wrapper = field.GetValue(entity);
var property = wrapper.GetType().GetProperty("Context");
var context = (ObjectContext)property.GetValue(wrapper, null);
return context;
}
Is there a way to get this result in EF Core?
No. EF Core does not have lazy loading yet. If it had, then, a proxy generated from it would eventually have a reference to the DbContext that loaded it. As of now, there is no such reference.
One could use dependency injection on the instance/entity at creation. To allow the owning dbcontext to be retrieved from the entity later.
eg
class Book
{
public readonly DBContext _dbcontext;
public Book(DBContext dbcontext)
{
_dbcontext = dbcontext;
}
}
There is no good way to do this. There seems to be no easy way to inject any code into the process after an entity object is constructed but before it is enumerated through in the calling code.
Subclassing InternalDbSet was something I considered but you can only fix calls to the .Find methods and the IQueryable implementation (the main way you'd use a DbSet) is out of reach.
So the only option I can see left is to not allow access to the DbSet at all but have accessor functions which will set the .Owner (or whatever you want to call it) property for me. This is messy since you would normally have to write a function for every query type you'd want to make, and the caller couldn't use LINQ any more. But we can use generics and callbacks to preserve most of the flexibility though it looks ugly. Here is what I came up with.
I am working on porting and cleaning up a complex system so I am not in a position to really test this yet but the concept is sound. The code may need further tweaking to work as desired. This should not have any penalties with eg pulling down the entire table before processing any records as long as you use EnumerateEntities to enumerate, instead of QueryEntities, but again I have yet to do any real testing on this.
private void InitEntity(Entity entity) {
if (entity == null) {
return;
}
entity.Owner = this;
// Anything you want to happen goes here!
}
private DbSet<Entity> Entities { get; set; }
public IEnumerable<Entity> EnumerateEntities() {
foreach (Entity entity in this.Entities) {
this.InitEntity(entity);
yield return entity;
}
}
public IEnumerable<Entity> EnumerateEntities(Func<DbSet<Entity>, IEnumerable<Entity>> filter) {
IEnumerable<Entity> ret = filter(this.Entities);
foreach (Entity entity in ret) {
this.InitEntity(entity);
yield return entity;
}
}
public T QueryEntities<T>(Func<DbSet<Entity>, T> filter) {
if (filter is Func<DbSet<Entity>, Entity>) {
T ret = filter(this.Entities);
this.InitEntity(ret as Entity);
return ret;
}
if (filter is Func<DbSet<Entity>, IEnumerable<Entity>>) {
IEnumerable<Entity> ret = filter(this.Entities) as IEnumerable<Entity>;
// You should be using EnumerateEntities, this will prefetch all results!!! Can't be avoided, we can't mix yield and no yield in the same function.
return (T)ret.Select(x => {
this.InitEntity(x);
return x;
});
}
return filter(this.Entities);
}
public void QueryEntities(Action<DbSet<Entity>> filter) => filter(this.Entities);

ASP.NET MVC - Attaching an entity of type 'MODELNAME' failed because another entity of the same type already has the same primary key value

In a nutshell the exception is thrown during POSTing wrapper model and changing the state of one entry to 'Modified'. Before changing the state, the state is set to 'Detached' but calling Attach() does throw the same error. I'm using EF6.
Please find my code below(model names have been changed to make it easier to read)
Model
// Wrapper classes
public class AViewModel
{
public A a { get; set; }
public List<B> b { get; set; }
public C c { get; set; }
}
Controller
public ActionResult Edit(int? id)
{
if (id == null)
{
return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
}
if (!canUserAccessA(id.Value))
return new HttpStatusCodeResult(HttpStatusCode.Forbidden);
var aViewModel = new AViewModel();
aViewModel.A = db.As.Find(id);
if (aViewModel.Receipt == null)
{
return HttpNotFound();
}
aViewModel.b = db.Bs.Where(x => x.aID == id.Value).ToList();
aViewModel.Vendor = db.Cs.Where(x => x.cID == aViewModel.a.cID).FirstOrDefault();
return View(aViewModel);
}
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult Edit(AViewModel aViewModel)
{
if (!canUserAccessA(aViewModel.a.aID) || aViewModel.a.UserID != WebSecurity.GetUserId(User.Identity.Name))
return new HttpStatusCodeResult(HttpStatusCode.Forbidden);
if (ModelState.IsValid)
{
db.Entry(aViewModel.a).State = EntityState.Modified; //THIS IS WHERE THE ERROR IS BEING THROWN
db.SaveChanges();
return RedirectToAction("Index");
}
return View(aViewModel);
}
As shown above line
db.Entry(aViewModel.a).State = EntityState.Modified;
throws exception:
Attaching an entity of type 'A' failed because another entity of the
same type already has the same primary key value. This can happen when
using the 'Attach' method or setting the state of an entity to
'Unchanged' or 'Modified' if any entities in the graph have
conflicting key values. This may be because some entities are new and
have not yet received database-generated key values. In this case use
the 'Add' method or the 'Added' entity state to track the graph and
then set the state of non-new entities to 'Unchanged' or 'Modified' as
appropriate.
Does anybody see anything wrong in my code or understand in what circumstances it would throw such error during editing a model?
Problem SOLVED!
Attach method could potentially help somebody but it wouldn't help in this situation as the document was already being tracked while being loaded in Edit GET controller function. Attach would throw exactly the same error.
The issue I encounter here was caused by function canUserAccessA() which loads the A entity before updating the state of object a. This was screwing up the tracked entity and it was changing state of a object to Detached.
The solution was to amend canUserAccessA() so that the object I was loading wouldn't be tracked. Function AsNoTracking() should be called while querying the context.
// User -> Receipt validation
private bool canUserAccessA(int aID)
{
int userID = WebSecurity.GetUserId(User.Identity.Name);
int aFound = db.Model.AsNoTracking().Where(x => x.aID == aID && x.UserID==userID).Count();
return (aFound > 0); //if aFound > 0, then return true, else return false.
}
For some reason I couldnt use .Find(aID) with AsNoTracking() but it doesn't really matter as I could achieve the same by changing the query.
Hope this will help anybody with similar problem!
Interestingly:
_dbContext.Set<T>().AddOrUpdate(entityToBeUpdatedWithId);
Or if you still is not generic:
_dbContext.Set<UserEntity>().AddOrUpdate(entityToBeUpdatedWithId);
seems to solved my problem smoothly.
It seems that entity you are trying to modify is not being tracked correctly and therefore is not recognized as edited, but added instead.
Instead of directly setting state, try to do the following:
//db.Entry(aViewModel.a).State = EntityState.Modified;
db.As.Attach(aViewModel.a);
db.SaveChanges();
Also, I would like to warn you that your code contains potential security vulnerability. If you are using entity directly in your view model, then you risk that somebody could modify contents of entity by adding correctly named fields in submitted form. For example, if user added input box with name "A.FirstName" and the entity contained such field, then the value would be bound to viewmodel and saved to database even if the user would not be allowed to change that in normal operation of application.
Update:
To get over security vulnerability mentioned previously, you should never expose your domain model as your viewmodel but use separate viewmodel instead. Then your action would receive viewmodel which you could map back to domain model using some mapping tool like AutoMapper. This would keep you safe from user modifying sensitive data.
Here is extended explanation:
http://www.stevefenton.co.uk/Content/Blog/Date/201303/Blog/Why-You-Never-Expose-Your-Domain-Model-As-Your-MVC-Model/
Try this:
var local = yourDbContext.Set<YourModel>()
.Local
.FirstOrDefault(f => f.Id == yourModel.Id);
if (local != null)
{
yourDbContext.Entry(local).State = EntityState.Detached;
}
yourDbContext.Entry(applicationModel).State = EntityState.Modified;
for me the local copy was the source of the problem.
this solved it
var local = context.Set<Contact>().Local.FirstOrDefault(c => c.ContactId == contact.ContactId);
if (local != null)
{
context.Entry(local).State = EntityState.Detached;
}
My case was that I did not have direct access to EF context from my MVC app.
So if you are using some kind of repository for entity persistence it could be appropiate to simply detach explicitly loaded entity and then set binded EntityState to Modified.
Sample (abstract) code:
MVC
public ActionResult(A a)
{
A aa = repo.Find(...);
// some logic
repo.Detach(aa);
repo.Update(a);
}
Repository
void Update(A a)
{
context.Entry(a).EntityState = EntityState.Modified;
context.SaveChanges();
}
void Detach(A a)
{
context.Entry(a).EntityState = EntityState.Detached;
}
Use AsNoTracking() where you are getting your query.
var result = dbcontext.YourModel.AsNoTracking().Where(x => x.aID == aID && x.UserID==userID).Count();
I have added this answer only because the problem is explained based on more complex data pattern and I found it hard to understand here.
I created a fairly simple application. This error occurred inside Edit POST action. The action accepted ViewModel as an input parameter. The reason for using the ViewModel was to make some calculation before the record was saved.
Once the action passed through validation such as if(ModelState.IsValid), my wrongdoing was to project values from ViewModel into a completely new instance of Entity. I thought I'd have to create a new instance to store updated data and then saved such instance.
What I had realised later was that I had to read the record from database:
Student student = db.Students.Find(s => s.StudentID == ViewModel.StudentID);
and updated this object. Everything works now.
I thought I'd share my experience on this one, even though I feel a bit silly for not realising sooner.
I am using the repository pattern with the repo instances injected into my controllers. The concrete repositories instantiate my ModelContext (DbContext) which lasts the lifetime of the repository, which is IDisposable and disposed by the controller.
The issue for me was that I have a modified stamp and row version on my entities, so I was getting them first in order to compare with the inbound headers. Of course, this loaded and tracked the entity that was subsequently being updated.
The fix was simply to change the repository from newing-up a context once in the constructor to having the following methods:
private DbContext GetDbContext()
{
return this.GetDbContext(false);
}
protected virtual DbContext GetDbContext(bool canUseCachedContext)
{
if (_dbContext != null)
{
if (canUseCachedContext)
{
return _dbContext;
}
else
{
_dbContext.Dispose();
}
}
_dbContext = new ModelContext();
return _dbContext;
}
#region IDisposable Members
public void Dispose()
{
this.Dispose(true);
}
protected virtual void Dispose(bool isDisposing)
{
if (!_isDisposed)
{
if (isDisposing)
{
// Clear down managed resources.
if (_dbContext != null)
_dbContext.Dispose();
}
_isDisposed = true;
}
}
#endregion
This allows the repository methods to re-new their context instance upon each use by calling GetDbContext, or use a previous instance if they so desire by specifying true.
I had this problem with local var and i just detach it like this:
if (ModelState.IsValid)
{
var old = db.Channel.Find(channel.Id);
if (Request.Files.Count > 0)
{
HttpPostedFileBase objFiles = Request.Files[0];
using (var binaryReader = new BinaryReader(objFiles.InputStream))
{
channel.GateImage = binaryReader.ReadBytes(objFiles.ContentLength);
}
}
else
channel.GateImage = old.GateImage;
var cat = db.Category.Find(CatID);
if (cat != null)
channel.Category = cat;
db.Entry(old).State = EntityState.Detached; // just added this line
db.Entry(channel).State = EntityState.Modified;
await db.SaveChangesAsync();
return RedirectToAction("Index");
}
return View(channel);
Problem causes of loaded objects with same Key, so first we will detach that object and do the the updating to avoid conflict between two object with the same Key
i mange to fix the issue by updating state. when you trigger find or any other query operation on the same record sate has been updated with modified so we need to set status to Detached then you can fire your update change
ActivityEntity activity = new ActivityEntity();
activity.name="vv";
activity.ID = 22 ; //sample id
var savedActivity = context.Activities.Find(22);
if (savedActivity!=null)
{
context.Entry(savedActivity).State = EntityState.Detached;
context.SaveChanges();
activity.age= savedActivity.age;
activity.marks= savedActivity.marks;
context.Entry(activity).State = EntityState.Modified;
context.SaveChanges();
return activity.ID;
}
I had a similar issue, after probing for 2-3 days found ".AsNoTracking" should be removed as EF doesn't track the changes and assumes there are no changes unless an object is attached. Also if we don't use .AsNoTracking, EF automatically knows which object to save/update so there is no need to use Attach/Added.
I encountered this error where
two methods, A & B, in a single controller both used the same instance of an ApplicationDbContext, and
method A called method B
private ApplicationDbContext db;
// api methods
public JsonResult methodA(string id){
Resource resource = db.Resources.Find(id);
db.Entry(resource).State = EntityState.Modified;
db.SaveChanges();
return methodB()
}
public JsonResult methodB(string id){
Resource resource = db.Resources.Find(id);
db.Entry(resource).State = EntityState.Modified;
db.SaveChanges();
return new JsonResult();
}
I changed method B to have a using statement and rely only on the local db2.
After:
private ApplicationDbContext db;
// api methods
public JsonResult methodA(string id){
Resource resource = db.Resources.Find(id);
db.Entry(resource).State = EntityState.Modified;
db.SaveChanges();
return methodB()
}
public JsonResult methodB(string id){
using (var db2 = new ApplicationDbContext())
{
Resource resource = db2.Resources.Find(id);
db2.Entry(resource).State = EntityState.Modified;
db2.SaveChanges();
}
return new JsonResult();
}
Similar to what Luke Puplett is saying, the problem can be caused by not properly disposing or creating your context.
In my case, I had a class which accepted a context called ContextService:
public class ContextService : IDisposable
{
private Context _context;
public void Dispose()
{
_context.Dispose();
}
public ContextService(Context context)
{
_context = context;
}
//... do stuff with the context
My context service had a function which updates an entity using an instantiated entity object:
public void UpdateEntity(MyEntity myEntity, ICollection<int> ids)
{
var item = _context.Entry(myEntity);
item.State = EntityState.Modified;
item.Collection(x => x.RelatedEntities).Load();
myEntity.RelatedEntities.Clear();
foreach (var id in ids)
{
myEntity.RelatedEntities.Add(_context.RelatedEntities.Find(id));
}
_context.SaveChanges();
}
All of this was fine, my controller where I initialized the service was the problem. My controller originally looked like this:
private static NotificationService _service =
new NotificationService(new NotificationContext());
public void Dispose()
{
}
I changed it to this and the error went away:
private static NotificationService _service;
public TemplateController()
{
_service = new NotificationService(new NotificationContext());
}
public void Dispose()
{
_service.Dispose();
}
Here what I did in the similar case.
That sitatuation means that same entity has already been existed in the context.So following can help
First check from ChangeTracker if the entity is in the context
var trackedEntries=GetContext().ChangeTracker.Entries<YourEntityType>().ToList();
var isAlreadyTracked =
trackedEntries.Any(trackedItem => trackedItem.Entity.Id ==myEntityToSave.Id);
If it exists
if (isAlreadyTracked)
{
myEntityToSave= trackedEntries.First(trackedItem => trackedItem.Entity.Id == myEntityToSave.Id).Entity;
}
else
{
//Attach or Modify depending on your needs
}
I solve this problem with a "using" block
using (SqlConnection conn = new SqlConnection(connectionString))
{
// stuff to do with data base
}
// or if you are using entity framework
using (DataBaseEntity data = new DataBaseEntity)
{
}
Here is where I get the idea https://social.msdn.microsoft.com/Forums/sqlserver/es-ES/b4b350ba-b0d5-464d-8656-8c117d55b2af/problema-al-modificar-en-entity-framework?forum=vcses is in spanish (look for the second answer)
you can use added method like;
_dbContext.Entry(modelclassname).State = EntityState.Added;
but in many case if you want to use more than one model at that time this won't work because entity is already attached to another entity. So, at that time you can use ADDOrUpdate Entity Migration method which simply migrates object from one to another and as a result you wouldn't get any error.
_dbContext.Set<modelclassname>().AddOrUpdate(yourmodel);
Clear all State
dbContextGlobalERP.ChangeTracker.Entries().Where(e => e.Entity != null).ToList().ForEach(e => e.State = EntityState.Detached);
Reasons I've encountered this error:
Did not use .AsNoTracking() when querying for existing entities. Especially when calling a helper function to check permissions.
Calling .Include() on a query and then trying to edit the parent. Example: var ent = repo.Query<Ent>().Include(e=>e.Ent2).First(); ...repo.Edit(e.Ent2); repo.Edit(e); If I'm going to edit a nested object, I try to separate these into separate query calls now. If you can't do that, set the child object to null and iterate through lists, detaching objects like this
Editing an old entity in a Put web call. The new item is already added to the repo, so modify that one and have it be saved in super.Put(). Example of what will throw an error: public void Put(key, newItem){ var old = repo.Query<Entity>().Where(e=>Id==key).First(); ... repo.Edit(old); super.Put(key,newItem); ... }
Multiple helper functions edit the same entity. Instead of passing the ID as a parameter into each function, pass a reference to the entity. Error solved!
In my case , I had wrote really two times an entity of same type . So I delete it and all things work correctly
This problem may also be seen during ViewModel to EntityModel mapping (by using AutoMapper, etc.) and trying to include context.Entry().State and context.SaveChanges() such a using block as shown below would solve the problem. Please keep in mind that context.SaveChanges() method is used two times instead of using just after if-block as it must be in using block also.
public void Save(YourEntity entity)
{
if (entity.Id == 0)
{
context.YourEntity.Add(entity);
context.SaveChanges();
}
else
{
using (var context = new YourDbContext())
{
context.Entry(entity).State = EntityState.Modified;
context.SaveChanges(); //Must be in using block
}
}
}

Nullable optional parameter

I am using the entity framework 4 with edmx files and POCOs within an asp.net mvc application.
First of all I have a person class which is mapped to a table in the database.
public class Person
{
public Int32 ID{get;set;}
public string Name{get;set;}
public Int32? ParentID{get;set;}
}
Then in my service layer I have the following function to retrieve all persons. If a parentID is supplied the persons retrieved will be the ones with that parentID:
public List<Person> Get(int? parentPersonID = null)
{
var persons = Repository().GetAll(c => c.ParentID == parentPersonID);
}
Finally, the Repository() function returns an IRepository<Person> which contains the method:
public IQueryable<TModel> GetAll(Expression<Func<TModel, bool>> predicate = null)
{
var result = ObjectSet.AsQuaryable(); //ObjectSet is a ObjectSet<Person> instance
if (predicate != null)
result = result.Where(predicate);
return result;
}
Now, the problem is that if I pass null as parentPersonID to the service layer, so as Get(null). Enumeration yields no results. However if I modify the service layer code to:
public List<Person> Get(int? parentPersonID = null)
{
var persons = Repository().GetAll(null);
}
everything works as expected.
Any ideas why is that?
EDIT:
If i replace the service layer function code with:
var persons = Repository().GetAll(c => c.ParentID.Equals(parentPersonID));
instead of:
var persons = Repository().GetAll(c => c.ParentID == parentPersonID);
it works as expected - the first line retrieves records from the DB whereas the second one does not.
I am still curious as to what is the difference in the Equals() and == in this case.
I suspect it's to do with how equality is being handled. Try this:
public List<Person> Get(int? parentPersonID = null) {
var persons = Repository().GetAll(parentPersonID == null ?
c => !c.ParentID.HasValue :
c => c.ParentID == parentPersonID);
...
}
This will change the predicate to be an explicit nullity check when you pass in a parentPersonID of null, rather than making it just match the value you've passed in. There may well be a more elegant way of expressing it, but it's worth at least trying that to start with.
(I assume that if you specify a parentPersonID of null you want to get all the people with a null parentPersonID, not just all the people... that would be a different change.)

Categories