避免将私有集合属性暴露给实体框架。 DDD原则

问题描述 投票:1回答:1

我尝试在C#集合see more here上遵守DDD原则

我注意到初始种子HasData的模型构建器方法依赖于ICollection的Add方法。从数据库更新/迁移过程调用时,有什么方法可以绕过或欺骗该方法?

直到现在我所做的一切都是按照这条路走的。

1)围绕名为ReadOnlyKollection的ICollection创建一个包装器

2)对模型进行私有ICollection,以避免向外界暴露集合。

3)暴露包装器制作过时添加和一些其他方法,如果使用将抛出NotImplementedException。

但是仍然可以使用Add方法尽管有过时的警告,因为仍然是公共的,并且需要在更新/迁移数据库进程上使用种子HasData方法。

我在考虑至少从包装类的Add方法中限制调用方法。

当HasData运行时我可以很好地知道调用成员,并且只允许此Method处理并为其他任何事件抛出异常。

请注意,无法使用CallerMethodName编译类型功能,因为会破坏ICollectoion接口契约。

有什么想法可以避免在DDD原则之后将私有收藏属性暴露给实体框架? (并且仍然增强了HasData方法来更新/迁移数据库进程)。看下面的一些代码..

public interface IReadOnlyKollection<T> : ICollection<T>
{
}

public class ReadOnlyKollection<T> : IReadOnlyKollection<T>
{
    private readonly ICollection<T> _collection;

    public ReadOnlyKollection(ICollection<T> collection)
    {
        _collection = collection;
    }

    public int Count => _collection.Count;
    public bool IsReadOnly => _collection.IsReadOnly;

    IEnumerator IEnumerable.GetEnumerator() => GetEnumerator();
    public IEnumerator<T> GetEnumerator() => _collection.GetEnumerator();

    public bool Contains(T item) => _collection.Contains(item);
    public void CopyTo(T[] array, int arrayIndex) => _collection.CopyTo(array, arrayIndex);

    [Obsolete]
    public void Add(T item) => _collection.Add(item); // CallerMethodName trick to be applied here or ??

    [Obsolete] 
    public void Clear() => throw new NotImplementedException();

    [Obsolete] 
    public bool Remove(T item) => throw new NotImplementedException();
}

public class StateProvince
{
    public StateProvince() //EF Constructor
    {
    }

    public StateProvince(string id, string name)
    : this(name)
    {
        Id = id;
    }

    public string Id { get; protected set; }
    public string Name { get; protected set; }

    public string CountryRegionId { get; protected set; }
    public virtual CountryRegion CountryRegion { get; protected set; }
}

public class CountryRegion
{
    public CountryRegion() //EF Constructor
    {
    }

    public CountryRegion(string id, string name)
    : this(name)
    {
        Id = id;
    }

    public string Id { get; protected set; }
    public string Name { get; protected set; }

    private readonly ICollection<StateProvince> _stateProvinces = new List<StateProvince>(); // Private collection for DDD usage
    public IReadOnlyKollection<StateProvince> StateProvinces => new ReadOnlyKollection<StateProvince>(_stateProvinces); // Public like read only collection public immutable exposure
}


EntityTypeBuilder<StateProvince> // Code reduced for brevity

builder.HasIndex(e => e.CountryRegionId);
builder.Property(e => e.Id).IsUnicode(false).HasMaxLength(3).ValueGeneratedNever();
builder.Property(e => e.CountryRegionId).IsRequired().IsUnicode(false).HasMaxLength(3);
builder.Property(e => e.Name).IsRequired().HasMaxLength(50);


EntityTypeBuilder<CountryRegion> builder // Code reduced for brevity

builder.Property(e => e.Id).IsUnicode(false).HasMaxLength(3).ValueGeneratedNever();
builder.Property(e => e.Name).IsRequired().HasMaxLength(50);

builder.HasMany(e => e.StateProvinces)
    .WithOne(e => e.CountryRegion)
    .HasForeignKey(e => e.CountryRegionId)
    .IsRequired()
    .OnDelete(DeleteBehavior.Restrict);

builder.HasData(GetData())  

private static object[] GetData()
{   
    return new object[]
    {
        new { Id = "AF", Name = "Afghanistan", IsDeleted = false, LastModified = DateTimeOffset.UtcNow  },
        new { Id = "AL", Name = "Albania", IsDeleted = false, LastModified = DateTimeOffset.UtcNow  },
        new { Id = "DZ", Name = "Algeria", IsDeleted = false, LastModified = DateTimeOffset.UtcNow  },
        new { Id = "AS", Name = "American Samoa", IsDeleted = false, LastModified = DateTimeOffset.UtcNow  },
c# entity-framework entity-framework-core
1个回答
5
投票

链接的帖子适用于EF6,而HasData方法适用于EF Core。在EF Core中,事情要简单得多,在这方面不需要任何技巧。

  • EF Core不需要ICollection<T>用于收集导航属性。返回IEnumerable<T>或派生接口/类的任何公共属性都按约定发现为集合导航属性。因此,您可以安全地将您的收藏品展示为IEnumerable<T>IReadOnlyCollection<T>IReadOnlyList<T>等。
  • EF Core不需要属性设置器,因为它可以配置为直接使用backing field

此外,不需要特殊的“EF构造函数”,因为EF Core支持constructors with parameters

话虽如此,您不需要自定义集合接口/类。样本模型可能是这样的:

public class CountryRegion
{
    public CountryRegion(string name) => Name = name;    
    public CountryRegion(string id, string name) : this(name) => Id = id;

    public string Id { get; protected set; }
    public string Name { get; protected set; }

    private readonly List<StateProvince> _stateProvinces = new List<StateProvince>(); // Private collection for DDD usage
    public IReadOnlyCollection<StateProvince> StateProvinces => _stateProvinces.AsReadOnly(); // Public like read only collection public immutable exposure
}

public class StateProvince
{
    public StateProvince(string name) => Name = name;
    public StateProvince(string id, string name) : this(name) => Id = id;

    public string Id { get; protected set; }
    public string Name { get; protected set; }

    public string CountryRegionId { get; protected set; }
    public virtual CountryRegion CountryRegion { get; protected set; }
}

并添加以下内容(最简单 - 适用于所有实体的所有属性)

modelBuilder.UsePropertyAccessMode(PropertyAccessMode.Field);    

或者CountryRegion的所有属性

builder.UsePropertyAccessMode(PropertyAccessMode.Field);

或仅为该导航属性

builder.HasMany(e => e.StateProvinces)
    .WithOne(e => e.CountryRegion)
    .HasForeignKey(e => e.CountryRegionId)
    .IsRequired()
    .OnDelete(DeleteBehavior.Restrict)
    .Metadata.PrincipalToDependent.SetPropertyAccessMode(PropertyAccessMode.Field);

就这样。您将能够使用所有EF核心功能,如Include / ThenInclude,“导航”LINQ到实体查询等(包括HasData)。支持字段允许EF Core在需要时添加/删除元素,甚至替换整个集合(如果字段不是只读的话)。

© www.soinside.com 2019 - 2024. All rights reserved.