To detach or not to detach? entity framework IBindingList issue

MY PROBLEM : I have a listobject that I want to persist to sql server and when I call .SaveChanges() on Entity Framework it will fail because some objects in the context are not valid.

MY QUESTION: HOW DO I PERSIST ONLY VALID CHANGES? I'll work on UI informing the client as to those that are not valid.

I'm working with a VSTO Excel workbook project and I'm trying to manage data crud on a ListObject.

I have a POCO class and Entity Framework.

I'm passing the entity into the ListObject as an IBindingList object for events.

When I go to .SaveChanges() on the entity it crashes because not all objects are valid, seems like an all or nothing.

So now I'm considering detaching invalid objects until they become valid and saving the valid items.

It's odd the event process on the ListObject ListChanged event.

Let me also share this: when you add a row to the list object this creates a new empty object which (unless you have no validation going on) will be an invalid entity.

    public partial class Sheet3
    {

        private DonorContext db = new DonorContext();
        private void Sheet3_Startup(object sender, System.EventArgs e)
        {
            db.Donors.Load();
            IBindingList donors = db.Donors.Local.ToBindingList();
            donors.ListChanged += donors_ListChanged;
            this.Donors.SetDataBinding(donors, "", "ID", "DonorName", "Address1", "Address2", "City", "State", "PostalCode", "Phone", "Email", "IsPOBox", "HasErrors");
        }
// Concider this nothing more than an event to hook into for informing 
// Entity Framework to save changes.
        void donors_ListChanged(object sender, ListChangedEventArgs e)
        {
            foreach (var itm in (IBindingList)sender)
            {
                Donor donor = (Donor)itm;
            }
        }
链接地址: http://www.djcxy.com/p/33568.html

上一篇: 分离的实体导致重复的ID问题

下一篇: 分离还是不分离? 实体框架IBindingList问题