Sean
Sean

Reputation: 2577

Entity Framework Many-to-Many Insert

I have three tables. Named: Merchants, MerchantNumberX, Numbers (numbers is used by many other entities -- this is just one example).

The Merchants table looks like:

MerchantGuid, MerchantName

The Numbers table looks like:

NumberGuid, PhoneNumber

The Xref table looks like:

MerchantGuid, NumberGuid

I know in entity framework I can do this:

var newNumber = new Number { NumberGuid = Guid.NewGuid(), PhoneNumber = "55555555555" };
Merchants.Numbers.Add(newNumber);

And this will insert the relationship into the Xref table between the two table entities. However, is there any other way to "relate" these tables together WITHOUT having a Merchant object?

For instance:

 var newNumber = new Number { NumberGuid = Guid.NewGuid(), PhoneNumber = "4444444444" };
 newNumber.MerchantGuid = alreadyKnownMerchantGuid;  // This is not available, by the way, just an example of something we are looking for in a many-to-many relationship.

However, newNumber gives me a "Merchants" property that just recursively repeats itself.

We are in the process of rewriting a lot of code and wondering if there is a quick way to make this relationship without having to make a call to the database to get a Merchant object since we already have the valid MerchantGuid.

Anyone help with this one?

Upvotes: 0

Views: 1393

Answers (1)

Slauma
Slauma

Reputation: 177133

However, is there any other way to "relate" these tables together WITHOUT having a Merchant object?

No. Many-to-many relationships with EF are independent associations, that means, there is no foreign key property available in your model. You need to manipulate relationships using the two collections. That's the only way.

But, see next point...

... if there is a quick way to make this relationship without having to make a call to the database to get a Merchant object since we already have the valid MerchantGuid.

To create the relationship you don't need to load the existing Merchant entity from the database. You can create a "stub" entity with the key property set to the valid MerchantGuid and then attach it to the context. For EF this is an entity in state Unchanged that behaves as if it had been loaded from the database:

var newNumber = new Number {
    NumberGuid = Guid.NewGuid(), PhoneNumber = "55555555555" };

var merchant = new Merchant {
    MerchantGuid = alreadyKnownMerchantGuid, Numbers = new HashSet<Number>() };
context.Merchants.Attach(merchant);

merchant.Numbers.Add(newNumber);

context.SaveChanges();

Here is no database query involved. SaveChanges will create a new Number record and a new relationship record in the join table.

Upvotes: 2

Related Questions