Linq2SQL: Select only some columns, but still able to submit changes

大城市里の小女人 提交于 2019-12-11 09:04:47

问题


I need to update a column in a table which contains a lot of rows. Each row has a some large TEXT columns in it, which i do not need for my update.

I'm using LinqPAD, and this is roughly, what i wanna do:

(from s in Table
where s.FK_ID == null 
select new{s.FK_ID, s.Datum, s.PBNummer}).ToList()

.ForEach(s => s.FK_ID = new Guid(...some new guid here...));

SubmitChanges();

This does not compile, as the properties of an anonymous class type are read-only.

If I do

(from s in Table
where s.FK_ID == null 
select s).ToList()

then I can update and save, but all columns are loaded, which takes a very long time and causes memory problems.

Is there a way to only load some columns but still have an object that i can update and save using SubmitChanges? Or do i have to switch to SQL statements?


回答1:


Firstly, if you don't have a primary key in the database, then you wouldn't be able to update via Linq-To-Sql. If you have a primary key, but just don't know which it is, you can find it in Linqpad by doing something like

var table =  (from t in Mapping.GetTables() 
              where t.TableName == "[Table]" select t).SingleOrDefault();

(from dm in table.RowType.DataMembers 
           where dm.DbType != null && dm.IsPrimaryKey 
           select dm.Name)
          .Dump("Primary Key");

Once you know the primary key, you can do something like the following, (I'm assuming the primary key is called Id)

var oldList = (from s in Table
          where s.FK_ID == null 
          select new{s.Id , s.FK_ID, s.Datum, s.PBNummer}).ToList() ;

This is similar to your query, except I have added the primary key

foreach(var r in oldList)
{
    Table t = new Table();
    t.Id        = r.Id ;

    Table.Attach(t);
    t.FK_ID   = new Guid(...some new guid here...));
}
SubmitChanges();



回答2:


Way to update specific columns of a database record in Linq to SQL is to create a View on the table containing large columns, and only include the “short” columns:

CREATE VIEW [dbo].[V_FooMax] AS
SELECT  OID, ID
FROM    dbo.FooMax

Since views based on single tables are updatable, an update on the view is performed as an update on the table:

using (var database = new DataContext())
{
  var fooView = database.V_FooMaxes
    .Where(foo => foo.OID == OID).FirstOrDefault();
  fooView.ID = newID;
  database.SubmitChanges();
}

Reference: http://devio.wordpress.com/2011/01/15/updating-a-single-column-in-linq-to-sql-using-a-view/

Also you can look at: http://devio.wordpress.com/2011/01/16/updating-a-single-column-in-linq-to-sql-summary/



来源:https://stackoverflow.com/questions/8223942/linq2sql-select-only-some-columns-but-still-able-to-submit-changes

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!