【问题标题】:Entity Framework 4.3.1 how to create associationsEntity Framework 4.3.1 如何创建关联
【发布时间】:2012-03-28 01:39:56
【问题描述】:

我的代码如下

public class User
{
    public int ID { get; set; }
    public int BillingAddressID { get; set; }
    public Address BillingAddress { get; set; }
    public IList<Shipment> Shipments { get; set; }
}

public class Address
{
    public int ID { get; set; }
    public string Street { get; set; }
    public string City { get; set; }
    public string ZipCode { get; set; }
}

public class Shipment
{
    public int ID { get; set; }
    public string State { get; set; }
    public int DeliveryAddressID { get; set; }
    public Address DeliveryAddress { get; set; }
    public User ShipUser { get; set; }
    //[ForeignKey("ShipUser")]
    public int ShipUserID { get; set; }
    //public int UserId { get; set; }
}

public class TestContext : DbContext
{
    public DbSet<User> Users { get; set; }
    public DbSet<Address> Addresses { get; set; }
    public DbSet<Shipment> Shipments { get; set; }

    protected override void OnModelCreating(DbModelBuilder modelBuilder)
    {
        modelBuilder.Entity<Shipment>().HasRequired(u => u.ShipUser)
            .WithMany(d => d.Shipments)
            .HasForeignKey(c => c.ShipUserID)
            .WillCascadeOnDelete(false);
    }
}
  1. 如果我删除覆盖方法,我会得到一个错误“SqlException: Introducing FOREIGN KEY constraint 'FK_Shipments_Users_ShipUserID' on table 'Shipments'可能会导致循环或多个级联路径。指定ON DELETE NO ACTION或ON UPDATE NO ACTION,或者修改其他 FOREIGN KEY 约束。 无法创建约束。查看以前的错误。”
  2. 如果我在 Shipment 类中删除 ShipUserID,它会正常工作,当我看到由 ef 创建的表时,我在表 Shipment 中发现了一个名为 Shipment_UserID 的列。我不知道为什么。
  3. 如果将类缩进键重命名为 UserID,它也可以正常工作。

我还是试试看,但我不知道原因,我需要一些关于 EF 关联的书。

【问题讨论】:

    标签: entity-framework code-first


    【解决方案1】:
    1. 如果您没有为一个关系指定没有 cascadeDelete=false 的映射,如果您从 Shipmentuser 有两个关系,它将创建多个级联路径。 按照惯例,您可以使用 public

      Public User ShipUser { get; set; }
      public int ShipUserID { get; set; }

    按照惯例,它将使用ShipUserID 作为外键。

    1. 如果删除 ShipUserID Ef 需要创建自己的外键来保持关系。那是您的“Shipment_UserID”

    2. rename the class indenty key to UserID我不明白你的意思。

    Here is a good tutorial

    开头

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2012-03-31
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-07-04
      • 1970-01-01
      相关资源
      最近更新 更多