繁体   English   中英

实体框架6,具有对多个其他表的引用的表

[英]Entity Framework 6, table with references to multiple other tables

我有一个项目,其中有很多表,需要地址:

  • 顾客
  • 订购
  • 供应商
  • ...还有很多。

我们正在尝试使用如下通用地址表来代替CustomerAddress,OrderAddress和VendorAddress表:

AddressId  (PK, int, identity, not null)
AddressType (int, not null, poss values: Customer, Order, Vendor, etc..)
ForeignKeyId (int, not null)
Name
Street
City
etc...

和一个客户表:

CustomerId (PK, int, identity, not null)
...other customer information...

如果我有一个客户(CustomerId = 56),那么可能会有这样的地址记录:

AddressId (some number)
AddressType = 1 (Customer)
ForeignKeyId = 56
Name, Street, City

这一切都很好。

但是,问题出在我要向系统中添加新客户的时候。 在EF中,我认为这意味着我必须添加客户SaveChanges() ,然后分别添加地址。

Customer c = new Customer { ... };
context.Customer.Add(c);
context.SaveChanges();    // In order to get the CustomerId to be filled in
Address a = new Address { AddressType = 1, ForeignKeyId = c.CustomerId };
context.Address.Add(a);
context.SaveChanges();

这在代码结构上引起了两个问题。 首先,事情发展的方式是,我们可能不会在同一位置添加客户和地址。 其次,更重要的是,这需要两个SaveChanges(),这意味着我们不再需要事务(或者我们必须进行自己的事务并随身携带)。

我想做的更多是这样的:

Customer c = new Customer { ... };
context.Customer.Add(c);
Address a = new Address { AddressType = 1 };
context.Address.Add(a);
// Somehow magic happens and Address can be associated with
// Customer as soon as we have a CustomerId assigned.
context.SaveChanges();  

我知道没有魔术,但是我有办法通过一个SaveChanges()完成我想要的吗?

编辑 :如果相关,这是数据库优先EF。

如果数据库在表之间没有关系,则必须先添加()每个对象,然后再保存(ChangeChanges)()。

两者之间的关系是什么,例如一对一,一对多?

建立关系可以让您这样编写代码:

Customer c = new Customer
{
    ...
    Address = new Address { AddressType = 1 }
};

context.Customer.Add(c);
context.SaveChanges();

如果您尚未建立数据库关系并且无法建立数据库关系,则应该能够在EM中虚拟化该关系。

在您的Context类文件中,修改

protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
    //default statement
    //throw new UnintentionalCodeFirstException();

    //establish the one-to-zero-or-one relation
    modelBuilder.Entity<Customer>()
        .HasOptional(c => c.Address);
}

将适当的属性添加到您的客户和地址类。 以一对一关系为例。

public virtual Address Address {get; set;} public virtual Address Address {get; set;}客户和public virtual Customer Customer {get; set;} public virtual Customer Customer {get; set;}在地址中

我将很快更新OnModelCreating()。 我有个会议要参加。 如果还有其他任何内容,只需将其放入评论中(希望我不太烦恼)。

编辑请参阅此SO答案以建立关系。

编辑2 IRT DB首先,只要表在相同的上下文中,您只需要一次SaveChanges()。 为确保整个DAO的上下文相同,请在实例化DAO时初始化上下文。

private DbEntities db = new DbEntities();

然后,您将始终使用该db上下文实例。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM