草庐IT

c# - 指定的架构无效。错误 : The relationship was not loaded because the type is not available

coder 2023-07-10 原文

我希望在我的Order 模型中引用OrderAddress 模型两次;一次作为 ShippingAddress,一次作为 BillingAdress

另一方面,我希望我的 OrderAddress 模型有一个 OrderAddresses 列表。

OrderAddress 模型


public enum AddressType
{
    Billing,
    Shipping,
    Contact
}
public class OrderAddress : BaseModel
{
    public AddressType AddressType { get; set; }
    public bool IsPrimary { get; set; }

    public string Address { get; set; }
    public string CityStateZip { get; set; }
    public string ContactName { get; set; }
    public string PhoneNumber { get; set; }
    public string FaxNumber { get; set; }
    public string EmailAddress { get; set; }

    public virtual ICollection<Order> Orders { get; set; }

    public virtual ApplicationUser User { get; set; }
}

订单模型


public class Order : BaseModel
{
    public DateTime OrderDate { get; set; }

    public int BillingAddressId { get; set; }
    public virtual OrderAddress BillingAddress { get; set; }

    public int ShippingAddressId { get; set; }
    public virtual OrderAddress ShippingAddress { get; set; }

    public virtual ApplicationUser User { get; set; }

}

流畅的 API


protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
    base.OnModelCreating(modelBuilder);

    modelBuilder.Entity<Order>()
                .HasRequired(m => m.ShippingAddress)
                .WithMany(t => t.Orders)
                .HasForeignKey(m => m.ShippingAddressId)
                .WillCascadeOnDelete(false);

    modelBuilder.Entity<Order>()
                .HasRequired(m => m.BillingAddress)
                .WithMany(t => t.Orders)
                .HasForeignKey(m => m.BillingAddressId)
                .WillCascadeOnDelete(false);
}

当我尝试运行 Update-Database 时,出现以下错误:

Schema specified is not valid. Errors: The relationship 'MyApp.Domain.DAL.Order_ShippingAddress' was not loaded because the type 'MyApp.Domain.DAL.OrderAddress' is not available.

我做错了什么?

最佳答案

这个错误有点神秘,所以我不确定这是否是你得到那个特定错误的原因,但我知道它会导致一些错误,所以你可以开始通过解决这个问题:

您拥有的是与一个类上的同一模型的两个一对多关系。这本身不是问题,但您必须将它们分开对待。换句话说,它们不能都具有相反的 Orders 关系,因为在关系上,没有办法知道哪个外键关系应该填充该列表。如果您只是将流畅的 API 定义更改为 .WithMany(t => t.Orders_Shipping).WithMany(t => t.Orders_Billing) 之类的内容,我认为将清除您的错误。

关于c# - 指定的架构无效。错误 : The relationship was not loaded because the type is not available,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22610063/

有关c# - 指定的架构无效。错误 : The relationship was not loaded because the type is not available的更多相关文章

随机推荐