Delete a record entity framework

I am receiving an exception:

Unable to update the EntitySet 'Session' because it has a DefiningQuery and no element exists in the element to support the current operation.

while trying to delete a row from a database table. The exception appears when calling SaveChanges() for the row which exists. Below is my code:

public static Func<DC21GPDEntities, string, IQueryable<Session>> compiledDeleteQuery =
    CompiledQuery.Compile((DC21GPDEntities ctx, string userId) =>
        (from rows in ctx.Sessions
         where rows.User_ID == userId
         select rows));

[HttpPost]
public ActionResult Index(string searchItem )
{
   try
   {
      string userId =searchItem.Trim();
      string successMessage 
                = "The session for User ID: " + userId + " has been cleared in Fascor.";

      dc21gpdContext.CommandTimeout = 180;

      Models.Session session = Queries.compiledDeleteQuery(dc21gpdContext, userId).FirstOrDefault();

      if (session == null)
          successMessage = "Session for User ID: " + userId + " does noe exist";
      else
      {
          dc21gpdContext.DeleteObject(session);
          dc21gpdContext.SaveChanges();
      }

      ViewData["SuccessMessage"] = successMessage;
      return View();
  }
  catch (Exception ex)
  {
     ViewData["SuccessMessage"] = "Failed to clear session";
     return View();
  }
}

If your Session table doesn't have primary key it is mapped as DefiningQuery which makes it read only. You cannot delete, insert or update records mapped to DefinedQuery unless you create stored procedures defining these operations and map them in the model.

Even after that it doesn't have to be enough. Entities are deleted by their key. You can define key in your entity model but the key must uniquely identify the record. By default EF will use all non-nullable, non-binary columns as a key. If this set of columns don't identify records uniquely you will have more problems with using the Session entity (for example delete operation will delete more than one record and SaveChanges will fail) - in such case the only option is adding a unique column to the table and use it as a key. Once you add PK to the table all these issue will be solved.


The message is telling what the problem is, just not very well. I'll try to elaborate.

Entity Framework by default generates queries for fetching objects. Your EntityContainer for the "Session" object has an explicit query, meaning that you EntityFramework has been told to use a specific piece of handwritten sql (or stored proc) to fetch the Sessions.

When you override that behavior, you also have to provide a query that tells it how to delete a session. Here is the documentation on how to add such a delete function to your Entity Framework Container.

链接地址: http://www.djcxy.com/p/64926.html

上一篇: 实体框架多对多地保存

下一篇: 删除一个记录实体框架