Search code examples
c#entity-frameworkentity-framework-4linq-to-entitiesmany-to-many

Entity Framework Does not Import Table with Super Key


I have 4 tables:

but when I create an entity framework model, why is tblRoleInProfile not generated?

enter image description here

I have a Linq TO SQL model that want to convert it to EF and now my table is not generated. How can I solve that?

UPDATE 1:

You consider we have some profiles and some roles. If we want Profile A has role 1 Insert a record in tblRoleInProperty and if we want Profile B has not Role 2 (If it exists) delete it's record from tblRoleInProperty. I don't want delete a profile. another problem is select new projection. Can any body guide me to write this query in EF:

var prs = from p in dc.tblProfiles
          join rp in dc.tblRoleInProfiles
              on p.ProfileId equals rp.ProfileId
          join r in dc.tblRoles
              on rp.RoleId equals r.RoleId
          select new
          {
              ProfileName = p.ProfileName,
              ProfileId = p.ProfileId,
              RoleName = r.RoleName,
              RoleId = r.RoleId
          };

Thanks


Solution

  • This is how EF works. EF is ORM tool - it tries to hide persistance details and junction table in many-to-many relation is exactly that detail you don't want to see in your object model.

    You can rewrite your query simply to:

    var prs = from p in dc.tblProfiles
              from r in p.tblRoles
              select new
                  {
                      ProfileName = p.ProfileName,
                      ProfileId = p.ProfileId,
                      RoleName = r.RoleName,
                      RoleId = r.RoleId
                  };
    

    Updating and deleting relations also works through navigation properties.

    Inserting role to profile:

    // Dummy objects so you do not need to load them from DB first. 
    // These objects must exist in database
    var p = new Profile { ProfileId = ... };
    var r = new Role { RoleId = ... };
    
    context.tblProfiles.Attach(p);
    context.tblRoles.Attach(r);
    
    p.tblRoles.Add(r);
    
    context.SaveChanges();
    

    Deleting role from profile:

    // Dummy objects so you do not need to load them from DB first. 
    // These objects must exist in database
    var p = new Profile { ProfileId = ... };
    var r = new Role { RoleId = ... };
    
    p.tblRoles.Add(r);
    
    context.tblProfiles.Attach(p);
    context.tblRoles.Attach(r);
    
    p.tblRoles.Remove(r);
    // another approach: 
    // context.ObjectStateManager.ChangeRelationshipState(p, r, x => x.tblRoles, EntityState.Deleted);
    
    context.SaveChanges();