0

我正在尝试使用 Code First 更新我在实体框架中设置的多对多关系。我创建了以下模型。

[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");
                     });
    }
}

这是添加/更新的控制器方法和保存添加/更新业务逻辑的服务器方法

[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 调用更新时调用的更新方法和相关方法。由于此 repo 继承了基本可跟踪实体 repo,因此它从基类运行更新。

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 特定调用都允许我的测试工作,而无需创建一堆 Fake Repositories。

4

1 回答 1

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

在运行了我所有的单元测试、集成测试和一些手动测试之后,一切都通过了,所以我对这个变化很好。

于 2013-04-09T20:58:22.970 回答