使用linq更新表

时间:2015-05-14 04:15:55

标签: c# linq

我想更新表但不能正常工作

以下是代码:

public Boolean setSectionTickSign(decimal Trans_ID, decimal Job_ID, string SectioName)
{
    string sectionames = "";
    Transcription_Master Trans_Mastr = new Transcription_Master();
    try
    {
        var Trans_Master = (from Trans_Mast in r2ge.Transcription_Master where Trans_Mast.Transcription_Id == Trans_ID && Trans_Mast.Entity_Id == Job_ID select new 
        {
            Trans_Mast.Completed_Trans_Sections
        }).Distinct().ToList();
        var complt_trans = Trans_Master.AsEnumerable().Where(dr = > dr.Completed_Trans_Sections != null).ToList();
        if (complt_trans.Count == 0) 
        {
            if (sectionames == "") 
            {
                Trans_Mastr.Completed_Trans_Sections = SectioName;
            }
        } 
        else
        {
            Trans_Mastr.Completed_Trans_Sections = "," + SectioName;
        }
        int sc = r2ge.SaveChanges();
    }
}

它没有更新数据库..它有什么问题?

2 个答案:

答案 0 :(得分:0)

你应该将这段代码更改为这样的东西:

 var Trans_Master = (from Trans_Mast in r2ge.Transcription_Master 
                     where Trans_Mast.Transcription_Id == Trans_ID 
                     && Trans_Mast.Entity_Id == Job_ID 
                     select Trans_Mast).Distinct().ToList();

在这种情况下,你的变量Trans_Maser将从集合中引用对象,因此将对从EF上下文获取的对象进行更改,而SaveChanges将给出正确的结果。

答案 1 :(得分:0)

解决了我自己的问题Transcription_Master Trans_Mastr = new Transcription_Master();无需创建新对象

public Boolean setSectionTickSign(decimal Trans_ID, decimal Job_ID, string SectioName)
{
    string sectionames = "";
    try
    {
        var empQuery = r2ge.Transcription_Master.Where(l => l.Transcription_Id == Trans_ID && l.Entity_Id == Job_ID).ToList();

        foreach (Transcription_Master Trans_Mastrr in empQuery)
        {
            if (empQuery.Count == 0)
            {
                if (sectionames == "")
                {
                    Trans_Mastrr.Completed_Trans_Sections = SectioName;
                }
            }
            else
            {
                Trans_Mastrr.Completed_Trans_Sections = Trans_Mastrr.Completed_Trans_Sections + "," + SectioName;
            }
        }
        int sc = r2ge.SaveChanges();
    }