开发者

Entity framework 4 CRUD creating errors

开发者 https://www.devze.com 2023-02-21 13:08 出处:网络
I have 3 related tables in my database. Farm ----> FarmCrops <----- Crops I\'m trying to update the a farm entity with a collection of crops but am running into problems. I\'ve been working on th

I have 3 related tables in my database.

Farm ----> FarmCrops <----- Crops

I'm trying to update the a farm entity with a collection of crops but am running into problems. I've been working on this with no success for hours now so any help would be greatly appreciated.

The error I'm receiving is this:

The object cannot be attached because it is already in the object context. An object can only be reattached when it is in an unchanged state.

My update logic is as follows (my apologies for the large amount of code. I'd just like to be as clear as possible):

            bool isNew = false;
            Farm farm;

            // Insert or update logic.
            if (viewModel.Farm.FarmId.Equals(Guid.Empty))
            {
                farm = new Farm
                {
                    FarmId = Guid.NewGuid(),
                    RatingSum = 3,
                    RatingVotes = 1
                };
                isNew = true;
            }
            else
            {
                farm = this.ReadWriteSession
                       .Single<Farm>(x => x.FarmId == viewModel.Farm.FarmId);

            }

            // Edit/Add the properties.
            farm.Name = viewModel.Farm.Name;
            farm.Owner = viewModel.Farm.Owner;
            farm.Address = viewModel.Farm.Address;
            farm.City = viewModel.Farm.City;
            farm.Zip = viewModel.Farm.Zip;
            farm.WebAddress = viewModel.Farm.WebAddress;
            farm.PhoneNumber = viewModel.Farm.PhoneNumber;
            farm.Hostel = viewModel.Farm.Hostel;
            farm.Details = viewModel.Farm.Details;
            farm.Latitude = viewModel.Farm.Latitude;
            farm.Longitude = viewModel.Farm.Longitude;
            farm.Weather = v开发者_运维技巧iewModel.Farm.Weather;

            // Add or update the crops.
            string[] cropIds = Request.Form["crop-token-input"].Split(',');
            List<Crop> allCrops = this.ReadWriteSession.All<Crop>().ToList();

            if (!isNew)
            {
                // Remove all previous crop/farm relationships.
                farm.Crops.Clear();
            }

            // Loop through and add any crops.
            foreach (Crop crop in allCrops)
            {
                foreach (string id in cropIds)
                {
                    Guid guid = Guid.Parse(id);
                    if (crop.CropId == guid)
                    {
                        farm.Crops.Add(crop);
                    }
                }
            }

            if (isNew)
            {
                this.ReadWriteSession.Add<Farm>(farm);
            }
            else
            {
                this.ReadWriteSession.Update<Farm>(farm);
            }
            this.ReadWriteSession.CommitChanges();

My update code within the ReadWriteSession is simple enough (GetSetName<T> just returns the types name from it's PropertyInfo.):

    /// <summary>
    /// Updates an instance of the specified type.
    /// </summary>
    /// <param name="item">The instance of the given type to add.</param>
    /// <typeparam name="T">The type of entity for which to provide the method.</typeparam>
    public void Update<T>(T item) where T : class, new()
    {
        this.context.AttachTo(this.GetSetName<T>(), item);
        this.context.ObjectStateManager.ChangeObjectState(item, EntityState.Modified);
    }


You are adding existing Crop objects (from the allCrops list) to the new Farm. When you connect a new entity to an existing one, the new entity automatically gets attached to the context. Therefore you get the error when you try to attach the Farm to the context the second time.

The Add<Farm>(farm) statement in your code is not even necessary to connect the Farm to the context, and if you have an existing Farm that is loaded from the context, it is already attached to the context.

The whole of your if (isNew) statement is unnecessary. Entity framework tracks object state itself, so you don't need to set the modified state.


you don't have to attach the "farm" object at the end, because it's already attached as modified when you change one of its properties. try removing the else statement at the end:

if (isNew)
{
   this.ReadWriteSession.Add<Farm>(farm);
}

Hope this helps :)


The problem is in your update method. You can't attach the Farm instance because you have loaded it from the same context so it is already attached and you don't need to call your Update at all because changes to attached objects are tracked automatically.

0

精彩评论

暂无评论...
验证码 换一张
取 消