如何使Ef Core完全忽略在实体中包装其他属性的对象?



我试图使EfCore忽略类似于拥有类型概念的包装对象。

我如何转动这个物体:

public class Entity
{
public Guid Id { get; set; }
public object SomeProperty { get; set; }
public ICollection<Item> Items { get; set; }
public ICollection<OtherItem> OtherItems { get; set; }
}
public class Item
{
public Entity Entity { get; set; }
public Guid EntityId { get; set; }
}
public class OtherItem
{
public Entity Entity { get; set; }
public Guid EntityId { get; set; }
}

Into this object

public class Entity
{
public Guid Id { get; set; }
public Aggregate Aggregate { get; set; } // This should not be mapped to the Database but only the properties
}
[Owned] // I think this is what i'm looking for
public class Aggregate
{
public object SomeProperty { get; set; }
public ICollection<Item> Items { get; set; }
public ICollection<OtherItem> OtherItems { get; set; }
public void SomeUsefulFunction()
{
// do Something Useful on the Aggregate
}
}

我希望EfCore完全忽略聚合对象并威胁其属性,就好像它们来自实体对象一样。我认为拥有实体的概念正是如此,但我得到以下错误:

Unable to determine the relationship represented by navigation 'Aggregate.OtherItems' of type 'ICollection<OtherItem>'. Either manually configure the relationship, or ignore thi
s property using the '[NotMapped]' attribute or by using 'EntityTypeBuilder.Ignore' in 'OnModelCreating'.

像这样?

public class Entity
{
public Guid Id { get; set; }

public Aggregate Aggregate => new Aggregate(this);
protected object SomeProperty { get; set; }
protected ICollection<Item> Items { get; set; }
protected ICollection<OtherItem> OtherItems { get; set; }
}
public class Aggregate
{
public object SomeProperty => _entity.SomeProperty;
public ICollection<Item> Items => _entity.Items;
public ICollection<OtherItem> OtherItems => _entity.OtherItems;

public Aggregate(Entity entity)
{
_entity = entity;
}
public void SomeUsefulFunction()
{
// do Something Useful on the Aggregate
}
}

public class SampleContext : DbContext
{
public DbSet<Entity> Entities { get; set; }
protected override void OnModelCreating(ModelBuilder modelBuilder)
{
modelBuilder.Entity<Entity>().Ignore(c => c.Aggregate);
}
}

PS只是在展示如何获取,你也可以很容易地使用set。

我建议您查看dotnet参考架构https://github.com/dotnet-architecture/eShopOnContainers。订购服务是使用DDD方法构建的- https://github.com/dotnet-architecture/eShopOnContainers/tree/dev/src/Services/Ordering。它有很好的例子如何建模聚合,域事件(Ordering.Domain文件夹),以及存储库实现以及EF实体(Ordering.Infrastructure文件夹)的配置。

还有几个解决方案模板可以避免键入样板代码:

  • https://github.com/jasontaylordev/CleanArchitecture
  • https://github.com/ardalis/CleanArchitecture

From microsoft docs:

遵循依赖倒置原则和领域驱动设计(DDD)原则的应用程序往往会得到类似的体系结构。多年来,这种架构有过许多名字。第一个名字是六边形架构,紧随其后的是端口和适配器。最近,它被引用为洋葱架构或清洁架构

相关内容

最新更新