最有效的方式更新列表项目与实体框架

本文关键字:项目 实体 框架 列表 更新 有效 方式 | 更新日期: 2023-09-27 18:10:02

我们的用户将有一个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();

有更干净的方法吗?

最有效的方式更新列表项目与实体框架

你是在寻找c#代码吗?

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

使用您给出的示例模型

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.