开发者

Linq update query - Is there no pretty way?

I want to update my database using a LINQ2SQL query.

However this seems for some reason to be a very ugly task compared to the otherwise lovely LINQ code.

The query needs to update two tables.

tbl_subscription
(
   id int,
   sub_name nvarchar(100),
   sub_desc nvarchar(500),
   and so on.
)

tbl_subscription2tags
(
   sub_id (FK to tbl_subscription)
   tag_id (FK to a table called tbl_subscription_tags)
)

Now down to my u开发者_C百科pdate function a send a tbl_subscription entity with the tags and everything.

I can't find a pretty way to update my database..

I can only find ugly examples where I suddenly have to map all attributes..

There most be a smart way to perform this. Please help.

C# Example if possible.

I have tried this with no effect:

public void UpdateSubscription(tbl_subscription subscription)
    {
        db.tbl_subscriptions.Attach(subscription);
        db.Refresh(System.Data.Linq.RefreshMode.OverwriteCurrentValues, subscription);
        db.SubmitChanges(System.Data.Linq.ConflictMode.FailOnFirstConflict);
    }

Source for this code is here: http://skyeyefive.spaces.live.com/blog/cns!6B6EB6E6694659F2!516.entry


Why don't just make the changes to the objects and perform a SubmitChanges to the DataContext?

using(MyDataContext dc = new MyDataContext("ConnectionString"))
{
  foreach(var foo in dc.foo2)
  {
   foo.prop1 = 1;
  }
  dc.SubmitChanges();
}

Otherwise you need to tell us more about the lifecycle of the object you want to manipulate

edit: forgot to wrap in brackets for using


Unless I'm misunderstanding your situation, I think that citronas is right.

The best and easiest way that I've found to update database items through LINQ to SQL is the following:

  1. Obtain the item you want to change from the data context
  2. Change whatever values you want to update
  3. Call the SubmitChanges() method of the data context.

Sample Code

The sample code below assumes that I have a data context named DBDataContext that connects to a database that has a Products table with ID and Price parameters. Also, a productID variable contains the ID of the record you want to update.

using (var db = new DBDataContext())
{
    // Step 1 - get the item from the data context
    var product = db.Products.Where(p => p.ID == productID).SingleOrDefault();
    if (product == null) //Error checking
    {
        throw new ArgumentException();
    }

    // Step 2 - change whatever values you want to update
    product.Price = 100;

    // Step 3 - submit the changes
    db.SubmitChanges();
}


I found out that you can use "Attach" as seen in my question to update a table, but apparently not the sub tables. So I just used a few Attach and it worked without having to run through parameters!

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜