Appernicus
Appernicus

Reputation: 464

Composite key with foreign keys entity framework

I have the following composite key:

Table RolesInProject

ProjectRole PK AND FK To ProjectRole

Account PK AND FK To Account

ProjectID PK AND FK To Project

I want to check if a certain account has a certain role in a project without writing any SQL using the entity framework. How can i do that? I also want to be able to change/delete the role of the account using the entity framework.

Upvotes: 0

Views: 72

Answers (1)

Giorgi Nakeuri
Giorgi Nakeuri

Reputation: 35780

You can check like:

if(dbContext.RolesInProject.Any(c=>c.ProjectRole == certainRole && 
                                   c.Account == certainAccount && 
                                   c.ProjectID == certainProject))
{
    DoSomething();
}
else
{
    DoSomethingElse();
}

To delete:

var item = dbContext.RolesInProject.FirstOrDefault(c=>c.ProjectRole == certainRole && 
                                                      c.Account == certainAccount && 
                                                      c.ProjectID == certainProject);

if(item != null)
{
    dbContext.RolesInProject.DeleteObject(item);
    dbContext.SaveChanges();
}

To change:

var item = dbContext.RolesInProject.FirstOrDefault(c=>c.ProjectRole == certainRole && 
                                                      c.Account == certainAccount && 
                                                      c.ProjectID == certainProject);

if(item != null)
{
    item.SomeColumn = someValue;
    dbContext.RolesInProject.ApplyChanges(item);
    dbContext.SaveChanges();
}

Upvotes: 1

Related Questions