2015-08-27 52 views
-5

我們的用戶將擁有List<EmailRecords>集合,並且只有其中一個將標記爲(bool)IsPrimary = true使用實體框架更新列表項的最有效方式

我想編寫實體框架代碼來更新它。

事情是這樣的:

UPDATE dbo.EmailRecords 
SET IsPrimary = 1 
WHERE EmailRecordId = @RecordId 

UPDATE dbo.EmailRecords 
SET IsPrimary = 0 
WHERE EmailRecordId != @RecordId 
    AND ParentRecordId = @ParentRecordId 

我的目標是:

public class EmailRecords 
{ 
    public int EmailRecordId { get; set; } 
    public int ParentRecordId { get; set; } 
    public string EmailAddress { get; set; } 
    public bool IsPrimary { get; set; } 
} 

我怎樣才能做到這一點與實體框架?

我在想這樣做這樣的事情:

foreach (var thisRecord in profile.EmailRecords) 
{ 
    if (thisRecord.EmailRecordId == thisId) 
    { 
     thisRecord.IsPrimary = true; 
    } 
    else 
    { 
     thisRecord.IsPrimary = false; 
    } 
} 

db.SaveChanges(); 

有一個更清潔的方式做到這一點?

+0

什麼是您的.net列表集合命名?提供一些代碼。 –

+0

你是指linq2sql還是實體框架? –

+0

嗨。所以你可能已經注意到了一些關於這個問題的看法。原因是這個問題現在聽起來像「這裏是想法,請給我編碼」。爲了得到一個好的答案,你應該先嚐試自己做一些事情,然後在這裏發帖,如果你遇到特定的問題,所以這個問題聽起來像「我有這個問題,試圖解決這個問題,但得到這個錯誤/問題」 – Andrei

回答

1

您是否在尋找C#代碼?

foreach(var record in profile.EmailRecords) 
{ 
    record.IsPrimary = record.EmailRecordId == recordId; 
} 
0

使用您給出的示例模型。

public class EmailRecords 
{ 
    public int EmailRecordId { get; set; } 
    public int ParentRecordId { get; set; } 
    public string EmailAddress { get; set; } 
    public bool IsPrimary { get; set; } 
} 

您可以使用這種組合的LINQ和代碼來取消設置此主要行爲。

// Change this Int32 to match your @RecordId and @ParentRecordId. Possibly parameterize this entire code snippet into a method. 
Int32 recordIdToChange = 1; 
Int32 parentRecordIdToChange = 1; 

// Set the new primary. 
EmailRecords emailRecordToSetToPrimary = profile.EmailRecords.Where(cs => cs.EmailRecordId == recordIdToChange).FirstOrDefault(); 
if (emailRecordToSetToPrimary != null){ 
    emailRecordToSetToPrimary.IsPrimary = true; 
} 

// Only unset those records whose id does not match the new primary AND is currently set as a primary. 
List<EmailRecords> emailRecordsToUnsetFromPrimary = profile.EmailRecords.Where(cs => cs.EmailRecordId != recordIdToChange && cs.IsPrimary == true && cs.ParentRecordId == parentRecordIdToChange).ToList(); 
foreach (EmailRecords emailRecordToUnsetFromPrimary in emailRecordsToUnsetFromPrimary){ 
    emailRecordToUnsetFromPrimary.IsPrimary = false; 
} 

// Perform your save on the emailRecords list collection. 
+0

這' emailRecords.Where(cs => cs.EmailRecordId == recordIdToChange).FirstOrDefault();'也可以進一步簡化爲'emailRecords.FirstOrDefault(cs => cs.EmailRecordId == recordIdToChange);' - 不需要'.Where ()'然後是'.FirstOrDefault()'之後... –