开发者

How do I create an Entity with Multiple Navigation Properties to the same Table?

This question has been asked in a few variations, but I believe that my issue is somewhat uni开发者_StackOverflowque.

I'm using the database-first approach with Entity Framework 4, and I am trying to map and Account to multiple Addresses, as well as map that same account to BillingAddress and ShippingAddress.

Here is my db schema: Account

  • ID
  • BillingAddressID
  • ShippingAddressID

Address

  • ID
  • AccountID

I have 3 foreign keys.

  1. Account.BillingAddressID to Address.ID
  2. Account.ShippingAddressID to Address.ID
  3. Address.ID to Account.ID

I would like to have the following POCO setup:

public class Account {

    public int ID { get; set; }        

    public virtual Address BillingAddress { get; set; }

    public virtual Address ShippingAddress { get; set; }

    public virtual ICollection<Address> Addresses { get; set; }
}

public class Address {

    public int ID { get; set; }        

    public int AccountID { get; set; }
}

Yet when I do this and try to create a new Account with an address, I get the following error:

"An error occurred while saving entities that do not expose foreign key properties for their relationships."

One thought I had was to shift the schema to a full many-to-many relationship between Account and Address. Then I guess I could put the Billing vs. Shipping vs. Other in the AccountAddresses table and use that in the foreign keys, but I am really curious if I can get it to work as is.

Account a = new Account();
// snip: add some account properties

Account.Addresses.Add(new Address {
    // snip: some properties here
});

context.SaveChanges();

==> ERROR (as mentioned above)

Any thoughts? Thanks!

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜