更新和保存功能相同

本文关键字:功能 保存 更新 | 更新日期: 2023-09-27 17:54:57

使用更新函数的代码在这里,它也可以工作

[HttpPost]
public bool SaveDefCompny(DefCompanyDTO DefCmpny)
{
    using (RPDBEntities db = new RPDBEntities())
    {
        using (TransactionScope trans = new TransactionScope())
        {
            //the problem is here incase of saving 
                var UpdateDefCmpnyId = (from CmpnyId in db.DefCompanies
                                        where CmpnyId.Id == DefCmpny.Id
                                        select CmpnyId).First();
                List<DefCompany> list = new List<DefCompany>();
                list.Add(UpdateDefCmpnyId);
                try
                {
                    foreach (DefCompany DefCmpny1 in list)
                    {
                        DefCmpny1.Id = DefCmpny1.Id;
                        DefCmpny1.ShortName = DefCmpny.ShortName;
                        DefCmpny1.FullName = DefCmpny.FullName;
                        DefCmpny1.ContactPerson = DefCmpny.ContactPerson;
                        DefCmpny1.Address1 = DefCmpny.Address1;

                        DefCmpny1.CompanyCity = DefCmpny.CompanyCity;
                        DefCmpny1.CompanyState = DefCmpny.CompanyState;
                        DefCmpny1.CompanyCountry = DefCmpny.CompanyCountry;
                        DefCmpny1.ZipPostCode = DefCmpny.ZipPostCode;
                        DefCmpny1.TelArea = DefCmpny.TelArea;
                        DefCmpny1.CurrentCurrencyCode = DefCmpny.CurrentCurrencyCode;

                        db.SaveChanges();
                        trans.Complete();
                    }
                }
                catch (Exception ex)
                {

                }
            }
            return false;
        }
}

当我尝试保存而不是更新代码行

var UpdateDefCmpnyId = (from CmpnyId in db.DefCompanies
                                            where CmpnyId.Id == DefCmpny.Id
                                            select CmpnyId).First();

给出null值,因此保存失败,因为记录是新的,不存在于数据库中,所以如何处理null在保存的情况下如何使用try catch,以便当值为null时,它继续保存添加

更新和保存功能相同

的代码

不如这样写:

var UpdateDefCmpnyId = (from CmpnyId in db.DefCompanies
                                    where CmpnyId.Id == DefCmpny.Id
                                    select CmpnyId).FirstOrDefault();
if(UpdateDefCmpnyId == null)
{
    //insert
    //(handle the id however you need to for insert. depending on your setup, you might be able to leave it empty and let the database put it in for you)
}
else
{
    //update
    //set the id as you do in the question
}