我有以下域模型,我试图确保它是使用 EF Core 3.1 的 COSMOSDB 提供程序创建的,但我不断收到错误。
模型类:
public class Application
{
public Site Site { get; set; } = new Site();
public Applicant Applicant { get; set; } = new Applicant();
public Agent Agent { get; set; } = new Agent();
}
public class Site
{
public Address Address { get; set; } = new Address();
}
public class Applicant
{
public Address Address { get; set; } = new Address();
}
public class Agent
{
public Address Address { get; set; } = new Address();
}
public class Address
{
public MapCoordinate MapCoordinate { get; set; } = new MapCoordinate();
public GeoLocation GeoLocation { get; set; } = new GeoLocation();
}
数据库上下文:
protected override void OnModelCreating(ModelBuilder modelBuilder)
{
modelBuilder.HasDefaultContainer("Applications");
modelBuilder.Entity<Address>(x => x.Property(y => y.GeoLocation).HasJsonConversion());
modelBuilder.Entity<Application>(x =>
{
x.HasKey(x => x.ApplicationId);
x.HasPartitionKey(x => x.ApplicationId);
x.OwnsOne(x => x.Site).OwnsOne(x => x.Address);
x.OwnsOne(x => x.Applicant).OwnsOne(x => x.Address);
x.OwnsOne(x => x.Agent).OwnsOne(x => x.Address);
});
}
错误:上线
x.OwnsOne(x => x.Site).OwnsOne(x => x.Address)
我得到:
System.InvalidOperationException: The type 'Address' cannot be marked as owned because a non-owned entity type with the same name already exists.
如何映射此关系,以便获得如下 Json 文档:
{
site : { address: { MapCoordinate : blah, GeoLocation: blah },
applicant : { address: { MapCoordinate : blah, GeoLocation: blah },
agent : { address: { MapCoordinate : blah, GeoLocation: blah }
}
最佳答案
在 efcore github 上发帖后事实证明,调用:
modelBuilder.Entity<Address>(x => x.Property(y => y.GeoLocation).HasJsonConversion());
将地址类型配置为标准实体而不是拥有的实体。我有效地尝试一次性配置地址类型的所有用途。目前这是不可能的,需要在每次使用该类型时完成,例如:
protected override void OnModelCreating(ModelBuilder modelBuilder)
{
modelBuilder.HasDefaultContainer("Applications");
modelBuilder.Entity<Application>(x =>
{
x.HasKey(x => x.ApplicationId);
x.HasPartitionKey(x => x.ApplicationId);
x.OwnsOne(x => x.Site).OwnsOne(x => x.Address, y =>
{
y.Property(p => p.GeoLocation).HasJsonConversion();
y.OwnsOne(p => p.MapCoordinate);
});
x.OwnsOne(x => x.Applicant).OwnsOne(x => x.Address, y =>
{
y.Property(p => p.GeoLocation).HasJsonConversion();
y.OwnsOne(p => p.MapCoordinate);
});
x.OwnsOne(x => x.Agent).OwnsOne(x => x.Address, y =>
{
y.Property(p => p.GeoLocation).HasJsonConversion();
y.OwnsOne(p => p.MapCoordinate);
});
});
}
EFCore 6.0 预计将提供批量配置功能
关于c# - EF Core 3.1 cosmosdb 拥有的实体,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/63044055/