在使用linq时防止重复代码

本文关键字:代码 linq | 更新日期: 2023-09-27 18:15:02

我目前正在使用c#和linq在SQL数据库中插入/更新数据。下面的代码工作得很好,但我觉得它很乱,而且是重复的。

你能看看下面的代码,并告诉我是否有一个更快的更新数据,而不是我必须复制我的代码

谢谢

Incident inc = new Incident
        {
            AccountID = AccountID,
            SiteID = siteID,
            DepartmentID = departmentID,
            LocationID = LocationID,
            QuestionCategoryID = CategoryID,
            IncidentSourceID = IncidentSourceID,
            IncidentTypeID = IncidentTypeID,
            NonConformanceTypeID = NonConID,
            ProductGroupID = ProductGroupID,
            ProductID = ProductID,
            ComponentID = ComponentID,
            ProductReference = prodRef,
            CurrentAssignedUserID = UserId,
            CurrentAssignedContactID = contactid,
            OriginalAssignedUser = UserId,
            OriginalAssignedContact = contactid,
            LoggedByUserID = logUserId,
            LoggedByContactID = logContactid,
            IncidentTitleID = IncidentTitleID,
            Title = IncidentTitle.ToString(),
            Description = problemDesc,
            Comments = comments,
            ActionsRequired = actions,
            RiskPriorityID = RiskPriorityTypeID,
            AffectedPartyID = affectedPartyID,
            ImpactLevel = Convert.ToInt32(impact),
            Justification = justification,
            EsculationDate = DateTime.Today,
            PriorityID = PriorityID,
            OriginalPriorityID = PriorityID,
            CreatedByUser = Convert.ToInt32(loggedInUserID),
            UpdatedBy = Convert.ToString(loggedInUserID),
            RiskID = RiskID,
            Active = true,
            StatusID = 1,
            DelayedDate = null,
            IncidentCloseDate = null,
            IncidentDate = DateTime.Now,
            IncidentPendingDate = DateTime.Now,
            LoggedDate = DateTime.Now,
            LastUpdated = DateTime.Now,
            LastActionTaken = DateTime.Now
        };
        // Save the data to the database
        if (Request.QueryString["IncidentID"] == null)
        {
            // Insert a new incident.
            db.Incidents.Add(inc);
            db.SaveChanges();
        }
        else
        {
            //update an existing incident.
            long ID = Convert.ToInt64(Request.QueryString["IncidentID"]);
            var record = db.Incidents.Where(i => i.IncidentID == ID).FirstOrDefault();
            record.AccountID = AccountID;
            record.SiteID = siteID;
            record.DepartmentID = departmentID;
            record.LocationID = LocationID;
            record.QuestionCategoryID = CategoryID;
            record.IncidentSourceID = IncidentSourceID;
            record.IncidentTypeID = IncidentTypeID;
            record.NonConformanceTypeID = NonConID;
            record.ProductGroupID = ProductGroupID;
            record.ProductID = ProductID;
            record.ComponentID = ComponentID;
            record.ProductReference = prodRef;
            record.CurrentAssignedUserID = UserId;
            record.CurrentAssignedContactID = contactid;
            record.OriginalAssignedUser = UserId;
            record.OriginalAssignedContact = contactid;
            record.LoggedByUserID = logUserId;
            record.LoggedByContactID = logContactid;
            record.IncidentTitleID = IncidentTitleID;
            record.Title = IncidentTitle.ToString();
            record.Description = problemDesc;
            record.Comments = comments;
            record.ActionsRequired = actions;
            record.RiskPriorityID = RiskPriorityTypeID;
            record.AffectedPartyID = affectedPartyID;
            record.ImpactLevel = Convert.ToInt32(impact);
            record.Justification = justification;
            record.EsculationDate = DateTime.Today;
            record.PriorityID = PriorityID;
            record.OriginalPriorityID = PriorityID;
            record.CreatedByUser = Convert.ToInt32(loggedInUserID);
            record.UpdatedBy = Convert.ToString(loggedInUserID);
            record.RiskID = RiskID;
            record.Active = true;
            record.StatusID = 1;
            record.DelayedDate = null;
            record.IncidentCloseDate = null;
            record.IncidentDate = DateTime.Now;
            record.IncidentPendingDate = DateTime.Now;
            record.LoggedDate = DateTime.Now;
            record.LastUpdated = DateTime.Now;
            record.LastActionTaken = DateTime.Now;
            db.SaveChanges();
        }

在使用linq时防止重复代码

只要设置一次属性,不管它是否存在

var id = Request.QueryString["IncidentID"];
var incidentId = String.IsNullOrEmpty(id) ? 0 : int.Parse(id);
var record = incidentId  !=0 ? 
   db.Incidents.FirstOrDefault(i => i.IncidentID == incidentId); : new Incident();
record.AccountID = AccountID;
record.SiteID = siteID;
record.DepartmentID = departmentID;
//etc.......
if (incidentId == 0)
{
     //set any fields here that are for add only
     record.CreatedByUser = ...
     db.Incidents.Add(record);
}
db.SaveChanges();
Incident inc;
if (Request.QueryString["IncidentID"] == null)
{
    inc = new Incident();
    // set properties that are specific to insert
    db.Incidents.Add(inc);
}
else 
{
    long ID = Convert.ToInt64(Request.QueryString["IncidentID"]);
    inc = db.Incidents.Where(i => i.IncidentID == ID).First();    
    // set properties that are specific to update
}
// set common properties
db.SaveChanges();

您可以这样做:

var incidentInitializer = new Action<Incident>(incident =>
{
  incident.AccountID = AccountID,
  incident.SiteID = siteID,
  ...
};
// Save the data to the database
if (Request.QueryString["IncidentID"] == null)
{
    // Insert a new incident.
    var inc = new Incident();
    incidentInitializer(inc);
    db.Incidents.Add(inc);
    db.SaveChanges();
}
else
{
    //update an existing incident.
    long ID = Convert.ToInt64(Request.QueryString["IncidentID"]);
    var record = db.Incidents.Where(i => i.IncidentID == ID).FirstOrDefault();
    incidentInitializer(record);
    db.SaveChanges();
}