使用linq时防止重复代码

时间:2013-05-23 08:27:30

标签: c# sql linq

我目前正在使用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();
        }

3 个答案:

答案 0 :(得分:0)

只需将您的属性设置为一次,无论天气如何,它都是现有实体。

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();

答案 1 :(得分:0)

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();

答案 2 :(得分:0)

您可以执行以下操作:

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();
}