Marcus L
Marcus L

Reputation: 4080

How do I change a foreign key association using Entity Framework?

Using ASP.NET Entity Framework, how can I change the Foreign Key association between two entities?

Here's an example scenario:

---------------     ----------------
|  Customer   |     |     Class    |
---------------     ----------------
| ID          |     | Desctription |
| Name        |     | Name         |
| ClassID (FK)|-----| ID           |
---------------     ----------------

A customer starts as a Class D customer. The more the customer spends, the classification will change to C, B or A. How can I do this using the EF?

I've set up a facade between the EF and my solution (because some operations requires operations outside EF), and I tried doing it this way:

customer.Context.Class.ID = facade.SelectClass(ClassID)

That returns a Business Object of Class, but the customer.Context.Class.ID wants a Data Layer object, and while I could do that, it would mean I break away from the set layer design.

Is there any way around this?

Sorry if the question is a bit messy or fuzzy.

Upvotes: 0

Views: 316

Answers (1)

Craig Stuntz
Craig Stuntz

Reputation: 126547

First, let's answer the question without all your extra layers. In straight EF, you might do:

var customer = Context.Customers.Where(c.Id == id).First();
customer.Class = Context.Classes.Where(c.Id == classId).First();

Now, how do you map that to your business objects? I can't debug your code without seeing it, but you need to expose some feature in your facade which maps business types to data layer types. I do this with expressions, but there are lots of solutions.

Upvotes: 1

Related Questions