Entity Framework how to use Navigation Property
I need populate a Pure Junction Table (containing only FK to other tables) when an EntityDataSource _Inserted
event is raised.
I have 3 Tables in my Database:
CmsJobs (JobId)
CmsJobsUsers (JobId FK, UserId FK)*
aspnet_Users (UserId)
*CmsJobsUsers is a PURE JUNCTION TABLE and it is not represented as an entity in the EF Model.
Here my code, I am NOT able开发者_如何学JAVA to save this data in CmsJobsUsers.
protected void uxEntityDataSourceCreateJob_Inserted(object sender, EntityDataSourceChangedEventArgs e)
{
Guid myUserListSelected = new Guid(uxListUsers.SelectedValue);// Guid for UserId in DropDownList
CmsJob myJob = (CmsJob)e.Entity; // My new Jobid
aspnet_Users myUser = new aspnet_Users();
myUser.UserId = myUserListSelected;
}
Any Ideas? Thanks for your help!
Here a useful resource: But I am not able to implment it: http://thedatafarm.com/blog/data-access/inserting-many-to-many-relationships-in-ef-with-or-without-a-join-entity/
You're not showing your EDM, but your CmsJob
entity should have a navigation property aspnet_Users
and the aspnet_User
entity should have a navigation property CmsJobs
. The simplest way to insert an entity into the junction table you need to fetch a User from the DB, add a CmsJob
to the users CmsJobs
collection, and save the user.
Again, you are not showing your attempt to persist anything to the DB, so I will write up a suggestion:
protected void uxEntityDataSourceCreateJob_Inserted(object sender, EntityDataSourceChangedEventArgs e)
{
using (var context = new YourEFObjectContext())
{
Guid myUserListSelected = new Guid(uxListUsers.SelectedValue);
CmsJob myJob = (CmsJob)e.Entity; // My new Jobid
aspnet_Users myUser = context.aspnet_Users.Single(u => u.UserId == myUserListSelected);
myUser.CmsJobs.Add(myJob);
context.SaveChanges();
}
}
精彩评论