How to update many to many navigation property only? - asp.net-mvc

i can update some properties use under method
public void Update(T entity, params Expression<Func<T, object>>[] properties)
{
_dbSet.Attach(entity);
DbEntityEntry<T> entry = _context.Entry(entity);
foreach (var selector in properties) { entry.Property(selector).IsModified = true; }
}
//repo.Update(entity, e => e.Name, e => e.Description);
but,i want to update navigation property only in many to many relationship
such like admin role adminrole i want to update adminrole table only

If you want to update just relation you can use simple tricks.
To add a new relation between admin and role you need to do:
Admin admin = new Admin { Id = adminId };
context.Admins.Attach(admin);
Role role = new Role { Id = roleId };
context.Roles.Attach(role);
// Create new relation on attached entities
admin.Roles.Add(role);
context.SaveChanges();
To remove existing relation between admin and role you can try this:
Admin admin = new Admin { Id = adminId };
Role role = new Role { Id = roleId };
// Simulate existing relation on detached entities
admin.Roles.Add(role);
context.Admins.Attach(admin);
// Remove existing relation on attached entities
admin.Roles.Remove(role);
context.SaveChanges();
In both scenarios you just need to know keys for admin and role.
Note: This is for scenario where you have real many-to-many (with junction table containing only keys).

Related

How can we give grant and revoke permissions by Entity Framework code-first?

All I want is to give the permissions to the user from Entity Framework (using the code first approach) that is like DDL, DML commands to a certain user.
The steps below will help you create user, create roles, assign user to roles, and limit their access depending on their role.
Open your Solution in Visual Studio
Tools > Nuget Package Manager Console > Enter Enable-Migrations
Open Migrations > Configuration.cs
Use this as your seed method;
protected override void Seed(ISPRC.Models.ApplicationDbContext context)
{
var userStore = new UserStore<ApplicationUser>(context);
var userManager = new UserManager<ApplicationUser>(userStore);
userManager.UserValidator = new UserValidator<ApplicationUser>(userManager)
{
AllowOnlyAlphanumericUserNames = false,
};
var roleManager = new RoleManager<IdentityRole>(new RoleStore<IdentityRole>(new ApplicationDbContext()));
// Create a User Role
if (!roleManager.RoleExists("Admin"))
{
var role = new IdentityRole();
role.Name = "Admin";
roleManager.Create(role);
}
if (!context.Users.Any(u => u.UserName == "admin#mail.com"))
{
var user = new ApplicationUser
{
UserName = "admin#mail.com",
Email = "admin#mail.com",
EmailConfirmed = true,
};
// Create User
userManager.Create(user, "Password#777");
// Add User to Admin Role
userManager.AddToRole(user.Id, "Admin");
}
}
To limit certain roles in accessing your controllers or actions, add [Authorize] or [Authorize(Roles="Admin,User")]
The controller below will only allow Logged-in users that are of Admin role. If they're role does not match the requirement, they will be automatically redirected to login page.
[Authorize(Roles = "Admin")]
public class AdminController : Controller
{
private ApplicationDbContext db = new ApplicationDbContext();
public ActionResult Accounts()
{
return View();
}
}
Tools > Nuget Package Manager Console > Enter Update-Database
You can use Custom Migration Operations, or you can switch to a database-first workflow, and manage the database schema with another tool, and periodically reverse engineer the schema into a code-based model.

How do i insert data already present in one table into another using Entity framework

Hi I have table called Users which already has id of users who are registered.This table is in different database which is named TrackUsers. Now I am using new database called Terms which has field called ID which should take all ID's from users table and insert into this table.For this i used database first approach.
I am using ASP.NET MVC Entity framework. Below is the code I am using in controller :
public class HomeController : Controller
{
private AppMarketplaceEntities db = new AppMarketplaceEntities();
private InstallTrackerEntities db1 = new InstallTrackerEntities();
public ActionResult Index()
{
List<int> gatewayUserId = new List<int>();
using (var ctx = new InstallTrackerEntities())
{
gatewayUserId = ctx.Gateway_Users.Select(f => f.GatewayuserUID).ToList();
}
using (var ctx2 = new AppMarketplaceEntities())
{
foreach (var id in gatewayUserId)
{
ctx2.AppTerms.Add(new AppTerm() { GatewayuserUID = id });
}
db.SaveChanges();
}
return View();
}
}
}
But still GatewayUserUID is showing null in Appterms table.
Assuming you have 2 .edmx files (and therefore different dbcontexts for each database), are you looking for something like this?
List<int> userids = new List<int>();
using(var ctx = new TrackUsersEntities())
{
userids = ctx.Users.Select(f => f.UserId).ToList();
}
using(var ctx2 = new OtherDatabaseEntities())
{
foreach(var id in userids)
{
ctx2.Terms.Add(new Term() { ID = id });
}
ctx2.SaveChanges();
}
As for where to place the code, I'd put it in the Services layer (if it exists), otherwise in the Controller class.

Save userid on database when create new object

I have a Controller where on the Create action I need the user ID.
Here's the controller.
public ActionResult Create(MyCreateViewModel model)
{
if (ModelState.IsValid)
{
var myobject = new MyObject
{
Attrib1 = DateTime.Now.Date,
Attrib2 = model.Etichetta,
UserId = // I need the user ID...
};
// Save the object on database...
return RedirectToAction("Index");
}
return View(model);
}
I'm using the UserProfile table provided with the SimpleMembership of MVC 4.
Which is the best practice in MVC 4 to manage the userID across the application?
Do I have to include a User attribute inside every Entity class?
Should I use a Session[] variable or what?
You can use this line to get the userId from the UserProfiles table.
var userId = WebSecurity.GetUserId(HttpContext.Current.User.Identity.Name);
You can also use this function to get the users complete profile, including any custom columns you may be populating.
public static UserProfile GetUserProfile()
{
using (var db = new UsersContext())
{
var userId = WebSecurity.GetUserId
(HttpContext.Current.User.Identity.Name);
var user = db.UserProfiles
.FirstOrDefault(u => u.UserId == userId);
if (user == null)
{
//couldn't find the profile for some reason
return null;
}
return user;
}
}

ASPNET MVC: autocomplete field but need to save the ID

I have a Person DB table that has a surname, name, and IdCity fields.
In the View, I've implemented an autocomplete field to let the user digit the city.
How should I design the ViewModel for handling the IdCity and how can I pass it to the controller? It is a string but I need to pass the id and eventually insert it in the DB if it does not exist there yet.
Receive the city name in your view action, then look if a city exists for this name. If it does, use its ID. If it doesn't create a new one, and use that ID:
public ActionResult Update(PersonModel model)
{
var city = _cityRepository.GetCityByName(model.CityName);
if (city == null) _cityRepository.Add(city);
// At this point city.Id contains your city Id
var person = new Person
{
...
CityId = city.Id,
...
};
// Proceed to save your Person object
}

symfony - adding a user to a group (sfGuardUserGroup) in a form

I'm trying to save some users in a custom admin form and I'd like to set them in a particular group, in the sfGuardUserGroup.
So If the user I've just created has an id of 25, then I'd expect an entry in the sfGuardUserGroup table with a user_id of 25 and a group_id of 8 (8 is my group id I want o add these users to.)
Could I do this in the form class, or in the processForm action?
I'm using doctrine and SF1.4
Thanks
This should do what you need:
<?php
class AdminUserForm extends sfGuardUserForm
{
public function configure()
{
//customise form...
}
public function save($con = null)
{
//Do the main save to get an ID
$user = parent::save($con);
//Add the user to the relevant group, for permissions and authentication
if (!$user->hasGroup('admin'))
{
$user->addGroupByName('admin');
$user->save();
}
return $user;
}
}
If you require this behaviour for all sfGuardUser's created you should put this logic in the model for sfGuardUser class. [example below]
// sfGuardUser class
public function save(Doctrine_Connection $conn = null) {
if (!$this->hasGroup('group_name'))
$this->addGroupByName('group_name', $conn);
parent::save($conn);
}
If you require this functionality only on this specific form, you should put the logic within the form. Adding logic to the processForm action would be incorrect as you would be placing business logic within the controller.

Resources