Reputation: 65
im persian and i dont know english very well ... sorry if i writing bad ! i see this question in this site several time but i cant fix my problem by them , so i ask again this is my code
using(DocumentationContext context = new DocumentationContext())
{
var userInstance = new UserInstance();
userInstance.UserID = user.UserID;
userInstance.User = user;
userInstance.InstanceID = item.InstanceID;
userInstance.Instance = item;
userInstance.Code = permission.Code;
userInstance.Direct = Direct;
userInstance.BaseCode = BaseCode;
userInstance.Create = Create;
userInstance.Edit = Edit;
userInstance.Delete = Delete;
context.UserInstances.Add(userInstance);
context.SaveChanges();
}
it is my last change , i have search a lot and cant find answer , thanks
Upvotes: 3
Views: 46
Reputation: 239270
One of or both item
and user
came from a different instance of DocumentationContext
. If you're going to use using
, then all your entities must be queried, updated, whatever in that same using
statement.
The better approach for safety-sake is to inject your context as a dependency to your controllers. Then in the setup for whatever DI container you choose to work with, you should be able to give your context a "request scope", which essentially means that it will only ever create one instance per request. That will ensure that you're never working with multiple instances of your context.
Upvotes: 2