实体类型不是当前上下文的模型的一部分

时间:2013-10-03 17:49:09

标签: c# asp.net-mvc entity-framework

我正在尝试记录客户详细信息表中的更改。为此我使用的是EF4

using (realstateEntities context = new realstateEntities())
{
    //Here the model is built**
    cadClientes cliente = new cadClientes();
    cliente.Nome = model.nome;
    ...
    cliente.observacao = model.observacao;

    //Here I am adding the model and saving the changes**
    context.cadClientes.Add(cliente);
    context.SaveChanges();                                

    //Now I am trying to log that operation** (Error is in following line)
     paramsOriginais = LogsController.PrintProperties("cadClientes", context.Entry(context.cadClientes).GetDatabaseValues());

}

我收到此错误:

  

System.InvalidOperationException:实体类型DbSet 1 is not part of the model for the current context.\r\n at System.Data.Entity.Internal.InternalContext.GetEntitySetAndBaseTypeForType(Type entityType)\r\n at System.Data.Entity.Internal.Linq.InternalSet 1.Initialize()\ r \ n at   System.Data.Entity.DbContext.Entry [TEntity](TEntity实体)\ r \ n at   realstate.Controllers.CadastrosController.clienteAdd(ClientesModel   模型,FormCollection表单)在c:\ Users \ guilherme \ Documents \ Visual中   工作室   2012 \项目\ realstate \ realstate \ \控制器CadastrosController.cs:行   303"

我在微软网站的这个例子中编写了我的代码:

using (var context = new UnicornsContext())
{
    var unicorn = context.Unicorns.Find(1);

    // Make a modification to Name in the tracked entity
    unicorn.Name = "Franky";

    // Make a modification to Name in the database
    context.Database.SqlCommand("update Unicorns set Name = 'Squeaky' where Id = 1");

    // Print out current, original, and database values
    Console.WriteLine("Current values:");
    PrintValues(context.Entry(unicorn).CurrentValues);

    Console.WriteLine("\nOriginal values:");
    PrintValues(context.Entry(unicorn).OriginalValues);

    Console.WriteLine("\nDatabase values:");
    PrintValues(context.Entry(unicorn).GetDatabaseValues());
}
你可以帮助我吗?感谢

1 个答案:

答案 0 :(得分:4)

context.Entry(context.cadClientes)引起。

cadClientesDbSetcadCliente个实体。实体 - cadCliente - 是模型的一部分,DbSet不是。我想你打算做的是

context.Entry(cliente)

这会起作用,它会记录添加的实体。