简体   繁体   中英

Update one to many table Entity Framework

I have a create User ASP.NET MVC 3 page - on the page there is a multiselect box of cars which is prepoulated from a Cars table in my DB. On save User I return a list of ints of CarIds that the user is associated with. I am using WCF services and Entity Framework 5.0 to get my data back to SQL Server and save to SQL server.

I then have a Table in my DB CarUser - it just contain a user Id and a client id - two FK's to the UserId in User Table and the CarId in the Cars table.

When I create a User it is updating the CarUser table is getting updated correctly (so for eg - it might look like this)

CarId UserId 2 4 3 4 4 4 5 4

So it is looking correct in that my CarUser table is showing User 4 associated with the 4 CarIds that were seleted from the Multi Select box. However the problem I am having is that it is re-creating the Cars in the cars table - so it is creating Car Id 9,10,11,12 for example but the details of them are exactly the same as 2,3,4,5

The code I have wrote for this is below:

    public User User_Create(User user, List<int> carIds)
    {
        DAL.CarUserWCFFServiceImpl carUser = new DAL.CarUserWCFFServiceImpl();

        // cal the DAL layer to do the create
        User newUser = carUser.User_Create(user);

        //call the DAL layer to create the cars linked to a user
        carUser.CarUserMapping_Create(newUser.UserID, carIds);

so my first DAL method (which is a layer below the one this code is listed from) call creates the User - then once I have the user so I have the ID, etc I call another method at the DAL layer passing in the UserID of the newly created User and then the list of carIds associated with the User.

The code from the 2nd method is below:

    public void CarUserMapping_Create(int userId, List<int> carIds)
    {
        using (CUEntities entities = new CUEntities())
        {
            User user = User_GetById(userId);
            entities.Users.Attach(userId);

            foreach (int carId in carIds)
            {
                Car car = Car_GetById(carId);

                user.Cars.Add(car);
                entities.ObjectStateManager.ChangeObjectState(user, System.Data.EntityState.Modified);
                entities.SaveChanges();
            }
        }
    }

Can anyone see something I am doing wrong? My other option I am thinking is take this away from Entity Framework and just call a stored procedure in CarUserMapping_Create

Maybe you need to add do the following:

public void CarUserMapping_Create(int userId, List<int> carIds)
{
    using (CUEntities entities = new CUEntities())
    {
        User user = User_GetById(userId);
        entities.Users.Attach(userId);

        foreach (int carId in carIds)
        {
            Car car = Car_GetById(carId);
            car.UserID = user.UserID;
            entities.Entry(car).State = EntityState.Modified;
            entities.SaveChanges();
        }
    }
}

You shuold not set the state like that. thats like raping the framework.

Instedad send the model instance ( entities ) down as a paramater to the methods that reads the reads the car and user. (and ofc. use the entities as the ObjectContext in the methods) like this:

using (CUEntities entities = new CUEntities())
{
    User user = User_GetById(entities , userId);


    foreach (int carId in carIds)
    {
        Car car = Car_GetById(entities, carId);
        car.UserID = user.UserID;
        entities.SaveChanges();
    }
}

that way, the entity framework will keep tract of the entity state

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM