我在尝试使用中间表将对象链接到地址列表时遇到问题,该中间表使用不同表的主键和地址的主键。我想要从对象到地址的一对多单向链接。
所以我创建了以下内容:
public class GlobalEntity
{
[Key]
public long Id { get; set; }
}
public class EntityAddress
{
[Required]
public int GlobalEntityId { get; set; }
public GlobalEntity GlobalEntity { get; set; } = null!;
[Required]
public int AddressId { get; set; }
public Address Address { get; set; } = null!;
}
public class Location
{
[Key]
public int Id { get; set; }
public string Name { get; set; } = null!;
[Required]
public int GlobalEntityId { get; set; }
public GlobalEntity GlobalEntity { get; set; } = null!;
public List<Address> Addresses { get; set; } = null!;
}
public class Manufacturer
{
[Key]
public int Id { get; set; }
public string Name { get; set; } = null!;
[Required]
public int GlobalEntityId { get; set; }
public GlobalEntity GlobalEntity { get; set; } = null!;
public List<Address> Addresses { get; set; } = null!;
}
public class Address
{
[Key]
public int Id { get; set; }
public string Label { get; set; } = null!;
public string Country { get; set; } = null!;
public string State { get; set; } = null!;
public string City { get; set; } = null!;
public string Zip { get; set; } = null!;
public string StreetAddress { get; set; } = null!;
[Required]
public int GlobalEntityId { get; set; }
public GlobalEntity GlobalEntity { get; set; } = null!;
}
这个程序将来可以和其他可能有List的对象一起扩展得越来越大。我目前想要实现的目标是使用一个中间表将制造商和位置链接到一个列表,而不必为每个表创建一个中间表。已经有一个 GlobalEntity 表,它为创建的每个对象生成唯一的 ID,例如位置、制造商和地址。
如何使用此中间表将位置链接到地址列表,最好不向地址添加导航属性?我希望使用 Fluent API 来实现这一点。
我尝试了以下链接,但不断出现错误。
protected override void OnModelCreating(ModelBuilder builder)
{
base.OnModelCreating(builder);
builder.Entity<EntityAddress>(ea =>
{
//Configures one-to-many relationship between Objects and Address through EntityAddress
ea.HasKey(e => new { e.GlobalEntityId, e.AddressId });
ea.HasOne(e => e.GlobalEntity)
.WithMany()
.HasForeignKey(e => e.GlobalEntityId);
ea.HasOne(e => e.Address)
.WithMany()
.HasForeignKey(e => e.AddressId);
});
builder.Entity<DigitalMarket>(dm =>
{
dm.HasMany(d => d.Addresses)
.WithMany()
.UsingEntity<EntityAddress>(
j => j.HasOne(ea => ea.Address).WithMany().HasForeignKey(ea => ea.AddressId),
j => j.HasOne(ea => ea.GlobalEntity).WithMany().HasForeignKey(ea => ea.GlobalEntityId)
);
});
}
实体中的第一个 WithMany() 会抛出一个错误,指出它需要参数,这需要来自 Address 的导航属性。但是当我将其更改为 WithOne() 时,我找不到配置它的方法,以便我实际上通过中间表链接列表地址。
任何解决此问题的帮助将不胜感激。