Click here to Skip to main content
15,907,906 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
Hi,
I have TableA(ID,Name and TableB_ID) and TableB(TableB_ID,Description), which have a 1 to many relationship.
After creating a context, I want to update a record in TableA, changing its TableB_ID value.
The thing is: I don't want to update the value of tableB_ID directly. I want to change that record by specifying a different "Description" value from TableB.

Do I have to write this or does entity framework do this for me?

THanks

What I have tried:

Changing the value of "Description" by using the navigation properties of TableA is not working.
Posted
Updated 21-Oct-16 11:51am

1 solution

I assume that description is unique. So you'll have to search for a matching description yourself. It is something like this:
C#
var descr = "something";
var tabB = context.TableB.FirstOrDefault(f => f.Description == descr );

if (tabB == null)
{
    // Assume TableB_ID is autonumber / identity in database.
    var newTabB = new TableB() { Description = descr };
    TableA.TableB = newTabB ;
    // Not sure if this line is required.
    context.TableB.Add(newTabB);
}
else
    TableA.TableB = tabB;

context.SaveChanges();
 
Share this answer
 
Comments
RuiBarreiros 21-Oct-16 19:03pm    
Your assumptions are correct! Thank you for your help! So, I have to write code to retrieve the corresponding TableB_ID from the Description field...
I was hoping Entity Framework would be able to do this for me, but I guess I'll have to learn more about EF.
Thanks!

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900