Question

I am having this issue updating my database 1 column at a time in asp.net using web api. I am trying to query a PUT to just update one value in the row instead of updating that one and setting the rest to null. I made a separate model outside of the controller to take in the update so I could do one at a time. When I hit this line db.Entry(user).State = EntityState.Modified; in the controller that is where it is erroring out. Any advice how I can fix this?

This is my separate ViewModel I am taking in in the put method:

namespace WebAPI.Models.ViewModels
{
    public class UserViewModel
    {
        public string FirstName { get; set; }
        public string LastName { get; set; }
    }
}

This is my controller calling in the method with the ViewModel in my parameter:

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;
            }

This is my DBContext file:

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; }
    }
}
Was it helpful?

Solution 2

The error comes from how you initialize the data context db.

The user object has been created in a separate db, so, when you are trying to update user, the current db doesn't know about this user object.

You could solve it by getting a 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();
 }

Alternatively, you could make sure that the data context you are using to create the user object is the same as the one that is trying to update the user.

Does this make sense to you?

OTHER TIPS

This always happened if your repository needs to dynamic accessing different Entity Framework DbContext which means different databases.

Check your data connection string in web.config file for each Entity Frmework DbContext.

For example:

 <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" />

check metadata in connectionString if it is pointing to a correct DbContext.

In this example, it is pointing to demx file called "CRMEntities".

Make sure you have the correct metadata part should be same as in edmx.

connectionString="metadata=res://*/Model1.csdl|res://*/Model1.ssdl|res://*/Model1.msl;"

Update the model to include the ID property.

Then do

var e = db.Entry(user);

e.Property(p => p.FirstName).Modified = true;

The property line is how you specify individual fields.

Your viewmodel is not a fully qualified User object. As such, you will need to get one.

This call, db.User.IsInRole("Admin"), seems to indicate you have the current user already. You should just modify that one and then submit that for changes

try
{
    db.User.FirstName = user.FirstName;
    db.User.LastName = user.LastName;

    db.Entry(db.User).State = EntityState.Modified;
    db.SaveChanges();
}

I've been getting this exception as well. I solved it by Right clicking on the Entity.edmx model in the diagram and Refreshing the connection to my database via "Update Model From Database".

I don't know why this worked, but it did, at least in my case.

This happened to me because someone created a new connection string in the app.config by cutting and pasting from an existing.

The result looked like this:

<connectionStrings>
    <add
        name="Db1Context"
        connectionString="metadata=res://*/Db1Context.csdl|res://*/Db1Context.ssdl|res://*/Db1Context.msl;..."
        providerName="System.Data.EntityClient"
    />
    <add
        name="Db2Context"
        connectionString="metadata=res://*/Db1Context.csdl|res://*/Db1Context.ssdl|res://*/Db1Context.msl;..."
        providerName="System.Data.EntityClient"
    />
</connectionStrings>

Note how Db2Context still references DbContext1 in its metadata...

In my case problem was one column was not present in corresponding entity file. One column mapping was there in edmx but was not present in charp file

Verify that the server is 64 or 32 bits and recompile the application.

I had the same issue receiving the exception when I tried to add an instance of my class to the DbSet. My problem was that the definition of the table in the database did not match my acutal object (2 non-null properties were missing in my model). I added the two properties to my class and the error was gone.

I had the same issue. My probleme was I do not put any mapping Entity/Table. After mapping my entity, the probleme was solved.

In my case, it was because of the wrong reference. I accidentally chose a system class that has the same name as my model class to be the reference.

For example, I had a model class called Site, and I accidentally chose the reference of using System.Security.Policy; where I should use using MyApplication.Models;

Hope it can help anyone who made such a silly mistake but struggling to figure out why.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top