How to Add table association in Entity Framework? - entity-framework

I have a table called User, a table called Permission and an association table so Many Users can have many Permissions.
User
ID - PK
Permission
ID - PK
UserPermission
UserID - PK (FK to user)
PermissionID - PK (FK to Permission)
In entity framework how can I add an entry to the association table to link a user to a permission?
I have tried the following with no luck:
var user = _Repository.Users.Single(u => u.ID == someUserID);
var permission = _Repository.Permissions.Single(p => p.ID == somePermissionID);
user.Permissions.Add(permission) //Not working
user.Permission.Attach(permission) //Still not working
_Repository.Save();
Can anyone help?

It should be :
UserPermission obj = new UserPermission { UserID = someUserID, PermissionID = somePermissionID };
_Repository.UserPermissions.AddObject(obj)
_Repository.Save();
Hope this will help.

Related

How to check Foreign Key to restrict SoftDelete?

I would like to know if it is possible to check FK when using SoftDelete with ASP.NET Boilerplate.
Example
Suppose these tables:
Roles: RoleId (PK) - Description
Users: UserId (PK) - Name - RoleId (FK with Roles)
Data:
Roles
1 - admin
2 - guest
Users
1 - admin - 1
2 - john - 2
So RoleId 1 should not be deleted if it was already assigned to an existing User.
Thanks in advance.
Soft delete just sets a flag to mark the record as deleted.
In ABP, you can write your own checks in ApplyAbpConceptsForDeletedEntity of your DbContext:
public class AbpProjectNameDbContext // : ...
{
// ...
protected override void ApplyAbpConceptsForDeletedEntity(EntityEntry entry, long? userId, EntityChangeReport changeReport)
{
CheckForeignKeys(entry);
base.ApplyAbpConceptsForDeletedEntity(entry, userId, changeReport);
}
private void CheckForeignKeys(EntityEntry entry)
{
var entity = entry.Entity;
if (!(entity is ISoftDelete))
{
// Foreign key constraints checked by database
return;
}
var role = entity as Role;
if (role != null)
{
if (Users.Any(u => u.Roles.Any(r => r.RoleId == role.Id)))
{
throw new UserFriendlyException("Cannot delete assigned role!");
}
}
}
}
Note that the template's RoleAppService actually removes users from the role before deleting it.
Briefly your goal is non-sense. SoftDelete feature marks the record as deleted and doesn't delete it physically. It's like Recycle Bin in Windows. So that you can undelete it anytime. From the database perspective, it's relationships are consistent. Because there's the data in the table.
Solution; when you prevent users to delete an in-use record you have to validate it yourself against your business rules.

Entity Framework Query based on relationship

If you have database tables with relationships as follows:
Person
PersonId (PK), Name
PersonDoesService
PersonId (FK), ServiceId (FK)
Service
ServiceId (PK), Type
Is it possible with Entity Framework in one statement to get all Persons that does one service based on serviceId?
The code below will do what you are asking. Make sure that your ServiceId exists.
var people = context.Service.First(s => s.ServiceId == theServiceIdIWant).Person // IEnumerable<Person>

Many to Many relation in JPA entities

I have 5 tables:
User:
username (PK)
Role:
role_id(PK)
role_name
Permissions:
perm_id(PK)
perm_name
User_role_rels:
ur_id(PK)
username(FK) -> user.username
role_id(FK) -> role.role_id
Role_perm_rels:
rp_id(PK)
role_id(FK) -> role.role_id
perm_id(FK) -> Permissions.perm_id
When I create JPA entities for these five tables I get List of UserRoleRels in User entity, but I would need list of permissions for this user. So, there should be a
List permList in User entity.
I am new to JPA and not sure how I can achieve this using annotations?
Since there is no direct relationship between User and Permission, it's correct that User doesn't have a permList collection property.
Assuming that your IDE has created correctly the entities according to your tables, you don't have ManyToMany annotations in your classes, but only OneToMany and ManyToOne. This makes a little cumbersome to fetch the permissions collection:
String userName = "";
User myUser = entityManager.find(User.class, userName);
for (UserRoleRels urr : myUser.getUserRoleRelsList()) {
Role r = urr.getRole();
for(RolePermRels rpr : r.getRolePermRelsList()) {
Permission p = rpr.getPermission();
}
}
If you don't have an extra property in the ManyToMany relation tables (in your case User_role_rels and Role_perm_rels), you can drop the PK field for both. This will let your IDE: (1) create simpler Entity classes, (2) avoid the creation of the Entity classes for the relation tables, (3) use the ManyToMany annotations. With that change, you'll be able to access the permissions more easily and in a more readable way:
String userName = "";
User myUser = entityManager.find(User.class, userName);
for (Role r : myUser.getRoleList()) {
List<Permission> pl = r.getPermissionList();
}
Useful links: EclipseLink UserGuide, JPA Wikibooks.

EF - how to add Relationship between 2 tables and insert refrenceId in the masterTable?

For example I have 3 tables:
Users -- the master table
{ Id, Name }
Permissions -- details
{ Id, PermissionTitle }
UserPermissions -- is a relation table between User and its Permissions
{ UserId , PermissionId}
I have 2 users in the tbUsers ( {1,"user1"} , {2,"user2"} )
and I have 3 permissions in the tbPermissions ( {1,"perm1"} , {2,"perm2"} , {3,"perm3"} )
now I want to add perm1 and perm2 to user1. What should I do in EF?
(I don't want to create/insert any Users or Permissions, I just want to add a relationship between them in the relation table)
because of EF, I don't have UserPermissions table in my dataModel.
If you want to load entities first you can do:
using (var context = new YourContext())
{
var user1 = context.Users.Single(u => u.Id == 1);
var perm1 = context.Permissions.Single(p => p.Id == 1);
var perm1 = context.Permissions.Single(p => p.Id == 2);
user1.Permissions.Add(perm1);
user1.Permissions.Add(perm2);
context.SaveChanges();
}
If you know Ids and you don't want to load entities first you can do:
using (var context = new YourContext())
{
var user1 = new User {Id = 1};
var perm1 = new Permission {Id = 1};
var perm1 = new Permission {Id = 2};
context.Users.Attach(user1);
context.Permissions.Attach(perm1);
context.Permissions.Attach(perm2);
user1.Permissions.Add(perm1);
user1.Permissions.Add(perm2);
context.SaveChanges();
}
These two approaches can be combined - for example you can load user from DB and create dummy objects only for permissions.
Users should have a navigation property Permissions so you need to add the permission to that collection. Should look similar to this:
user.Permissions.Add(permission1);
user.Permissions.Add(permission2);
context.SaveChanges();

Accessing table with only foreign Keys in Entity Data Framework

i am new to Entity Data framework
i have tables
Actions ( Actionid (pk) ,Actionname , ... )
Roles ( Roleid(pk) , Rolename , .... )
ActionRoles( Actionid(pk,fk) , Roleid(fk) ) [Mapping Table]
Please Suggest me the LINQ to get the RoleNames for Perticular ActionID
(Note : there is No class created with Name ActionRoles in entitydesigner.cs as because it doesn't have any other column name then ActionId and RoleID )
Thank you in Advance
When you have a link table like this, adding all tables to the Entity Model should create 2 way relationship Properties between the 2 end tables, hiding the link table completely allowing you to access via something like:
IEnumerable<string> roleNames = Entities.Actions
.First(a => a.Actionid == actionid)
.Roles
.Select(r => r.Rolename);
where actionid is an int variable containing the actionid you're interested in.
For a discussion of how to handle many-to-many relationships such as this (both foreign keys must be in the ActionRoles primary key as indicated in the comment to your question), see these tutorials:
For EF 4.0: http://www.asp.net/entity-framework/tutorials/the-entity-framework-and-aspnet-–-getting-started-part-5
For Ef 4.1: http://www.asp.net/entity-framework/tutorials/updating-related-data-with-the-entity-framework-in-an-asp-net-mvc-application