使用 select 新关键字将 linq 更新为 sql 值

update linq to sql values with select new keyword

如何使用具有匿名类型的 select 新关键字将 linq 更新为 sql 值,因为我正在使用 var 关键字和 select 我需要的新查询但它 returns 这样的错误

Compiler Error Message: CS0200: Property or indexer 'AnonymousType#1.Code' cannot be assigned to -- it is read only

这是我的代码:

var ProjectView12 = (from x in db.Projects
select new 
{
    add = db.Locations.Where(y = > y.ID == x.RegionID).FirstOrDefault().Name,
    Province = db.Locations.Where(y = > y.ID == x.ProvinceID).FirstOrDefault().Name,
    District = db.Locations.Where(y = > y.ID == x.DistrictID).FirstOrDefault().Name,
    Code = x.Code,
    Name = x.Name,
    ProjectIdentificationDate = db.Milestones.Where(y = > y.ProjectID == x.ID && y.StageID == 1 && y.ComponentID == 1 && y.ModuleID == 1).FirstOrDefault().Date.ToString(),
    ProjectLat = Convert.ToDecimal(x.Lat),
    ProjectLong = Convert.ToDecimal(x.Lon),
    Remarks = db.Milestones.Where(y = > y.ProjectID == x.ID && y.StageID == 1 && y.ComponentID == 1 && y.ModuleID == 1).FirstOrDefault().Remarks.ToString(),
}).ToList();

foreach(var item in ProjectView12) 
{
    item.Code = txtSubProjectCode.Text;
    item.Name = txtSubProjectName.Text;
    item.ProjectLat = Convert.ToDecimal(txtLatitude.Text);
    item.ProjectLong = Convert.ToDecimal(txtLongitude.Text);
    item.ProjectIdentificationDate = txtDate.Text;
    item.Remarks = txtRemarks.Text;
} //    txtLocation.Text = item.Region + ">" + item.Province + ">" + item.District;

try 
{
    db.SubmitChanges();
}
catch (Exception ex) 
{
    throw ex;
}

好吧,你会收到编译器错误,因为 - 正如它所说 - 匿名类型的属性在 C# 中是只读的。

更根本的是,即使您 可以 修改它们,您也必须期望 LINQ to SQL 反转您放入投影中的任何内容以便更新原始表。这对我来说似乎是一个相当高的要求 - 特别是在这种特殊情况下 Remarks 属性。

基本上,为了更新数据库,您需要更改从您的表映射的实体。查询 select 相关实体,然后您可以根据需要在客户端代码中从这些实体中进行投影 - 只要您仍然有对要修改的实体的引用。