获取"实体类型<model>不是当前上下文模型的一部分."

Sha*_*awn 15 c# asp.net entity-framework put dbcontext

我在使用web api在asp.net中一次更新我的数据库1列时遇到此问题.我试图查询PUT只更新行中的一个值而不是更新那个值并将其余值设置为null.我在控制器之外做了一个单独的模型来接受更新,所以我可以一次做一个.当我db.Entry(user).State = EntityState.Modified;在控制器中点击该行时,它出错了.有什么建议我怎么解决这个问题?

这是我在put方法中使用的单独的ViewModel:

namespace WebAPI.Models.ViewModels
{
    public class UserViewModel
    {
        public string FirstName { get; set; }
        public string LastName { get; set; }
    }
}
Run Code Online (Sandbox Code Playgroud)

这是我的控制器在我的参数中使用ViewModel调用方法:

public HttpResponseMessage PutUser(int id, UserViewModel user)
        {
            HttpResponseMessage response;

            if (db.User.IsInRole("Admin"))
            {
                try
                {
                        db.Entry(user).State = EntityState.Modified;
                        db.SaveChanges();
                }
                catch (DbUpdateConcurrencyException)
                {
                    if (!UserExists(id))
                    {
                        response = new HttpResponseMessage(HttpStatusCode.NotFound);
                        return response;
                    }
                    else
                    {
                        throw;
                    }
                }

                response = new HttpResponseMessage(HttpStatusCode.NoContent);
                return response;
            }
Run Code Online (Sandbox Code Playgroud)

这是我的DBContext档案:

public partial class Entities : DbContext
    {
        public Entities()
            : base("name=Entities")
        {
        }

        protected override void OnModelCreating(DbModelBuilder modelBuilder)
        {
            throw new UnintentionalCodeFirstException();
        }
        public virtual DbSet<User> Users { get; set; }
    }
}
Run Code Online (Sandbox Code Playgroud)

Chi*_*rld 25

如果您的存储库需要动态访问不同的Entity Framework DbContext(这意味着不同的数据库),则总会发生这种情况.

检查web.config文件中的每个Entity Frmework DbContext的数据连接字符串.

例如:

 <add name="CRMEntities" connectionString="metadata=res://*/CRMEntities.csdl|res://*/CRMEntities.ssdl|res://*/CRMEntities.msl;provider=System.Data.SqlClient;provider connection string=&quot;data source=Your Data Source;initial catalog=CRM;integrated security=True;MultipleActiveResultSets=True;App=EntityFramework&quot;" providerName="System.Data.EntityClient" />
Run Code Online (Sandbox Code Playgroud)

检查connectionString中的元数据是否指向正确的DbContext.

在此示例中,它指向名为"CRMEntities"的demx文件.


The*_*son 14

该错误来自初始化数据上下文的方式db.

用户对象是在单独创建的db,因此,当您尝试更新时user,当前的数据库不知道该user对象.

您可以通过获取用户来解决它

try
{
    // or check on FirstName and LastName if you don't have a user id
    var updatedUser = db.Users.SingleOrDefault(x => x.id == id);

    updatedUser.FirstName = user.FirstName;
    updatedUser.LastName = user.LastName;

    db.Entry(updatedUser).State = EntityState.Modified;
    db.SaveChanges();
 }
Run Code Online (Sandbox Code Playgroud)

或者,您可以确保用于创建user对象的数据上下文与尝试更新用户的数据上下文相同.

你能理解这个吗?


小智 5

确保您有正确的元数据部分应该与 edmx 中的相同。

connectionString="metadata=res://*/Model1.csdl|res://*/Model1.ssdl|res://*/Model1.msl;"
Run Code Online (Sandbox Code Playgroud)