Linq2SQL: Update object not created in datacontext

后端 未结 3 1704
孤独总比滥情好
孤独总比滥情好 2021-01-13 15:01

Normally when you update an object in linq2sql you get the object from a datacontext and use the same datacontext to save the object, right?

What\'s the best way to

相关标签:
3条回答
  • 2021-01-13 15:10

    I think you have 2 options here:

    1) Attach the object to the DataContext on which you will do your save 2) Using the primary key on your object, grab an instance that is attached to your context (e.g. do a FirstOrDefault()), and then copy the data over from the modified object to the object that has a context (reflection might be useful here).

    Rick Strahl has a very good blog article on attaching entities to a context at http://www.west-wind.com/weblog/posts/134095.aspx, particularly in regards to some of the problems you might encounter.

    0 讨论(0)
  • 2021-01-13 15:26

    To update an existing but disconnected object, you need to "attach" it do the data context. This will re-use the existing primary key etc. You can control how to handle changes- i.e. treat as dirty, or treat as clean and track future changes, etc.

    The Attach method is on the table - i.e.

    ctx.Customers.Attach(customer); // optional bool to treat as modified
    
    0 讨论(0)
  • 2021-01-13 15:29

    I am hoping you can help. I am developing a tiered website using Linq to Sql. I created a new class(or object) in DBML designer called memberState. This object is not an actual table in the database. I have this method in my middle layer:

    public override IEnumerable(memberState) GetMembersByState(string @state)<br/>
    {<br/>
    using (BulletinWizardDataContext context = DataContext)<br/>
    {<br/>
    IEnumerable(memberState) mems = (from m in context.Members<br/>
    join ma in context.MemberAddresses<br/>
    on m.UserId equals ma.UserId<br/>
    join s in context.States<br/>
    on ma.StateId equals s.StateId<br/>
    where s.StateName == @state<br/>
    select new memberState<br/>
    {<br/>
    userId = m.UserID,<br/>
    firstName = m.FirstName,<br/>
    middleInitial = m.MiddleInitial,<br/>
    lastName = m.LastName,<br/>
    createDate = m.CreateDate,<br/>
    modifyDate = m.ModifyDate<br/>
    }).ToArray(memberState)();<br/>
    return mems;
    }
    }
    

    The tables in my joins (Members, States, and MemberAddresses are actual tables in my Database). I created the object memberStates so I could use it in the query above (notice the Select New memberState. When the data is updated on the web page how do I persist the changes back to the Member Table? My Member Table consists of the following columns: UserId, FirstName, MiddleInitial, LastName, CreateDate, ModifyDate. I am not sure how save the changes back to the database.

    Thanks,

    0 讨论(0)
提交回复
热议问题