我正在尝试使用Code First更新我在Entity Framework中设置的多对多关系。我创建了以下模型。
[Serializable]
public class ClientFormField : FormField
{
public ClientFormField()
{
CanDisable = true;
}
public virtual ClientFormGroup Group { get; set; }
public virtual ICollection<ClientValue> Values { get; set; }
public virtual ICollection<LetterTemplate> LetterTemplates { get; set; }
}
[Serializable]
public class CaseFormField : FormField
{
public CaseFormField()
{
CanDisable = true;
}
public virtual CaseFormGroup Group { get; set; }
public virtual ICollection<LetterTemplate> LetterTemplates { get; set; }
public override IEnumerable<ValidationResult> Validate(ValidationContext validationContext)
{
foreach (var val in base.Validate(validationContext))
yield return val;
}
}
[Serializable]
public class SystemField : TrackableEntity
{
public string Name { get; set; }
public string Value { get; set; }
public string VarName { get; set; }
public virtual SystemFieldType SystemFieldType { get; set; }
public int TypeId { get; set; }
public ICollection<LetterTemplate> LetterTemplates { get; set; }
public override IEnumerable<ValidationResult> Validate(ValidationContext validationContext)
{
if (string.IsNullOrWhiteSpace(Name))
yield return new ValidationResult("System field must have a name.", new[] { "SystemFieldName" });
if (string.IsNullOrWhiteSpace(Value))
yield return new ValidationResult("System field must have a value.", new[] { "SystemFieldValue" });
var regex = new Regex(@"^[a-zA-Z0-9-_]+$");
if (!string.IsNullOrWhiteSpace(VarName) && !regex.IsMatch(VarName))
yield return
new ValidationResult("Varname can only contain alphanumeric, underscore, or hyphen",
new[] { "SystemFieldVarName" });
if (TypeId <= 0)
yield return new ValidationResult("System Field must have a type.", new[] { "SystemFieldType" });
}
}
[Serializable]
public class LetterTemplate : TrackableEntity
{
public LetterTemplate()
{
ClientFields = new Collection<ClientFormField>();
CaseFields = new Collection<CaseFormField>();
SystemFields = new Collection<SystemField>();
}
public string Name { get; set; }
public string Data { get; set; }
public virtual ICollection<ClientFormField> ClientFields { get; set; }
public virtual ICollection<CaseFormField> CaseFields { get; set; }
public virtual ICollection<SystemField> SystemFields { get; set; }
public override IEnumerable<ValidationResult> Validate(ValidationContext validationContext)
{
if(string.IsNullOrWhiteSpace(Name))
yield return new ValidationResult("Form Template must have a name", new[] { "Name" });
if(string.IsNullOrWhiteSpace(Data))
yield return new ValidationResult("Form Template must have content", new[] { "Data" });
}
}
以下是LetterTemplate类的配置。
public class LetterTemplateConfiguration : BaseTrackableEntityConfiguration<LetterTemplate>
{
public LetterTemplateConfiguration()
{
HasMany(c => c.ClientFields).WithMany(c => c.LetterTemplates)
.Map(m =>
{
m.MapLeftKey("LetterTemplateId");
m.MapRightKey("ClientFormFieldId");
m.ToTable("LetterTemplateClientFields");
});
HasMany(c => c.CaseFields).WithMany(c => c.LetterTemplates)
.Map(m =>
{
m.MapLeftKey("LetterTemplateId");
m.MapRightKey("CaseFormFieldId");
m.ToTable("LetterTemplateCaseFields");
});
HasMany(c => c.SystemFields).WithMany(c => c.LetterTemplates)
.Map(m =>
{
m.MapLeftKey("LetterTemplateId");
m.MapRightKey("SystemFieldId");
m.ToTable("LetterTemplateSystemFields");
});
}
}
以下是Add / Update的控制器方法和保存Add / Update
的业务逻辑的服务器方法[HttpPost]
[ValidateAntiForgeryToken]
[ValidateInput(false)]
public ActionResult Manage(LetterTemplate template)
{
if(ModelState.IsValid)
{
if (_letterTemplateService.Save(template) != null)
return RedirectToAction("List");
}
ViewBag.ClientFields = _clientFieldService.GetAllFields().OrderBy(f => f.Name);
ViewBag.CaseFields = _caseFieldService.GetAllFields().OrderBy(f => f.Name);
ViewBag.SystemFields = _systemFieldService.GetAllFields().OrderBy(f => f.Name);
return View(template);
}
public LetterTemplate Save(LetterTemplate template)
{
var dbTemplate = template;
if (template.Id > 0)
{
dbTemplate = _letterTemplateRepo.GetById(template.Id);
dbTemplate.Name = template.Name;
dbTemplate.Data = template.Data;
}
dbTemplate.ClientFields.Clear();
foreach (var field in _clientFieldRepo.All().Where(field => template.Data.Contains("~~" + field.VarName + "~~")))
dbTemplate.ClientFields.Add(field);
dbTemplate.CaseFields.Clear();
foreach (var field in _caseFieldRepo.All().Where(field => template.Data.Contains("~~" + field.VarName + "~~")))
dbTemplate.CaseFields.Add(field);
dbTemplate.SystemFields.Clear();
foreach (var field in _systemFieldRepo.All().Where(field => template.Data.Contains("~~" + field.VarName + "~~")))
dbTemplate.SystemFields.Add(field);
return template.Id <= 0 ? _letterTemplateRepo.Add(dbTemplate) : _letterTemplateRepo.Update(dbTemplate);
}
以下是添加/更新信函模板的视图。
@section RightContent
{
<h4>Manage</h4>
<form method="POST" action="/LetterTemplate/Manage" id="templateForm">
<div id="toolbar">
<div style="float: left;padding: 3px 0px 0px 10px;">
@Html.LabelFor(m => m.Name)
@Html.TextBoxFor(m => m.Name)
</div>
<div class="item" onclick=" $('#templateForm').submit(); ">
<span class="save"></span>Save
</div>
<div class="item" onclick=" window.location = '/LetterTemplate/List'; ">
<span class="list"></span>Back To List
</div>
</div>
<div class="formErrors">
@Html.ValidationSummary()
</div>
@Html.HiddenFor(m => m.Id)
@Html.HiddenFor(m => m.Active)
@Html.HiddenFor(m => m.IsDeleted)
@Html.TextAreaFor(m => m.Data)
@Html.AntiForgeryToken()
</form>
}
当我从视图中创建新模板时,一切正常。正如我所料,我在“多对多”关系表中填充了字段。当我试图更新应该清除所有现有关系并建立新关系的关系时,没有任何事情发生。这些表根本不受影响。我已经阅读了几个不同的帖子,关于更新多个表但没有发现任何可以修复我的问题的问题。这是我第一次尝试使用EF代码进行多对多,并且事先遵循了许多教程,但似乎无论我做什么,EF都不会更新关系表。
更新
添加新模板时生成的查询:
DECLARE @0 nvarchar = N'Test',
@1 nvarchar = N'<p>~~case_desc~~</p>
<p>~~fname~~</p>
<p>~~lname~~</p>
',
@2 bit = 1,
@3 bit = 0,
@4 int = 2,
@5 int = 2,
@6 DateTime2 = '2013-04-08T16:36:09',
@7 DateTime2 = '2013-04-08T16:36:09'
insert [dbo].[LetterTemplates]([Name], [Data], [Active], [IsDeleted], [CreatedById], [ModifiedById], [DateCreated], [DateModified])
values (@0, @1, @2, @3, @4, @5, @6, @7)
DECLARE @0 int = 2,
@1 int = 1
insert [dbo].[LetterTemplateClientFields]([LetterTemplateId], [ClientFormFieldId])
values (@0, @1)
DECLARE @0 int = 2,
@1 int = 2
insert [dbo].[LetterTemplateClientFields]([LetterTemplateId], [ClientFormFieldId])
values (@0, @1)
DECLARE @0 int = 2,
@1 int = 3
insert [dbo].[LetterTemplateClientFields]([LetterTemplateId], [ClientFormFieldId])
values (@0, @1)
在更新时生成的查询:
DECLARE @0 nvarchar = N'Test',
@1 nvarchar = N'<p>~~case_desc~~</p>
<p> </p>
<p>~~fname~~</p>
<p> </p>
<p>~~dob~~</p>
',
@2 bit = 1,
@3 bit = 0,
@4 int = 2,
@5 int = 2,
@6 DateTime2 = '2013-04-08T16:23:12',
@7 DateTime2 = '2013-04-08T16:33:15',
@8 int = 1
update [dbo].[LetterTemplates]
set [Name] = @0, [Data] = @1, [Active] = @2, [IsDeleted] = @3, [CreatedById] = @4, [ModifiedById] = @5, [DateCreated] = @6, [DateModified] = @7
where ([Id] = @8)
更新
我的存储库模式有2个基类泛型类。基本可跟踪实体存储库和基本存储库。基本可跟踪实体repo处理确保已删除的项目被软删除,获取未删除的项目以及管理createdby / modifiedby和createdDate / UpdatedDate。基本仓库处理剩余的基本CRUD操作。下面是我通过LetterTemplateRepository调用update时调用的更新方法和相关方法。由于此repo继承了基本可跟踪实体repo,因此它从基类运行update。
public override T Update(T entity)
{
return Update(entity, false);
}
public override T Update(T entity, bool attachOnly)
{
InsertTeData(ref entity);
entity.ModifiedById = CurrentUserId;
entity.DateModified = DateTime.Now;
_teDB.Attach(entity);
_db.SetModified(entity);
if (!attachOnly) _db.Commit();
return entity;
}
private void InsertTeData(ref T entity)
{
if (entity == null || entity == null) return;
var dbEntity = GetById(entity.Id);
if (dbEntity == null) return;
_db.Detach(dbEntity);
entity.CreatedById = dbEntity.CreatedById;
entity.DateCreated = dbEntity.DateCreated;
entity.ModifiedById = dbEntity.ModifiedById;
entity.DateModified = dbEntity.DateModified;
}
DbContext中的SetModified方法只是将EntityState设置为Modified。我在单元测试中使用Fake DbContext和DbSet,因此我通过DbContext扩展任何EF特定的调用,以允许我的测试工作,而不必创建一堆假存储库。
答案 0 :(得分:0)
原来问题出在InsertTeData方法中。当它分离我从数据库中提取的实体以确保创建并创建日期时,它导致我正在使用的实体丢失有关多对多关系的所有信息。我的猜测是实体跟踪的工作方式,它们都有相同的密钥。
我已经删除了InsertTeData方法,现在将所有内容作为默认值管理在抽象TrackableEntity类的构造函数中,现在一切正常。
public override T Update(T entity, bool attachOnly)
{
entity.ModifiedById = CurrentUserId;
entity.DateModified = DateTime.Now;
_teDB.Attach(entity);
_db.SetModified(entity);
if (!attachOnly) _db.Commit();
return entity;
}
在运行我的所有单元测试,集成测试和一些手动测试之后,一切都通过了,所以我对此更改很好。