Entity framework 实体框架4.3.1如何创建关联
我的代码如下所示Entity framework 实体框架4.3.1如何创建关联,entity-framework,code-first,Entity Framework,Code First,我的代码如下所示 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 i
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);
}
}
公共类用户
{
公共int ID{get;set;}
public int billingaddress{get;set;}
公共广播计费地址{get;set;}
公共IList装运{get;set;}
}
公共课堂演讲
{
公共int ID{get;set;}
公共字符串Street{get;set;}
公共字符串City{get;set;}
公共字符串ZipCode{get;set;}
}
公共舱位装运
{
公共int ID{get;set;}
公共字符串状态{get;set;}
public int DeliveryAddressID{get;set;}
公共地址传递地址{get;set;}
公共用户ShipUser{get;set;}
//[外国钥匙(“船舶用户”)]
public int ShipUserID{get;set;}
//public int UserId{get;set;}
}
公共类TestContext:DbContext
{
公共数据库集用户{get;set;}
公共数据库集地址{get;set;}
公共数据库集{get;set;}
模型创建时受保护的覆盖无效(DbModelBuilder modelBuilder)
{
modelBuilder.Entity().HasRequired(u=>u.ShipUser)
.有许多(d=>d.装运)
.HasForeignKey(c=>c.ShipUserID)
.WillCascadeOnDelete(假);
}
}
user
的fromshipping
的关系,它将创建多个级联路径。
按照惯例,你可以使用公共密码
公共用户ShipUser{get;set;}
public int ShipUserID{get;set;}
ShipUserID
作为外键
将类indenty key重命名为UserID
我不明白你的意思