我们的用户将拥有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; }
}
如何使用Entity Framework执行此操作?
我正在考虑做这样的事情:
foreach (var thisRecord in profile.EmailRecords)
{
if (thisRecord.EmailRecordId == thisId)
{
thisRecord.IsPrimary = true;
}
else
{
thisRecord.IsPrimary = false;
}
}
db.SaveChanges();
有更简洁的方法吗?
答案 0 :(得分:1)
您是否正在寻找C#代码,这些内容是什么?
foreach(var record in profile.EmailRecords)
{
record.IsPrimary = record.EmailRecordId == recordId;
}
答案 1 :(得分: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.