根据我的经验,我可以使用EntityFrameWork(带有视图的MVC 5控制器,使用EntityFramework)为Job和任何其他不是从IdentityUser派生的类生成CRUD的控制器和视图。我想在我的应用程序中有一个功能,其中角色管理员admin将能够删除同一用户表中的其他用户。如何使用EF生成控制器和视图?任何帮助,将不胜感激。谢谢!
public class User : IdentityUser
{
public string FirstName { get; set; }
public string LastName { get; set; }
public ICollection<Job> Jobs { get; set; }
}
public class Job
{
public int Id JobId {get; set;}
public string JobDetails {get; set;}
public bool isDone {get; set;}
public virtual User User {get; set;}
}
public class ApplicationDbContext : IdentityDbContext<User>
{
public ApplicationDbContext()
: base("DefaultConnection")
{
}
public DbSet<Job> Jobs { get; set; }
}
}
答案 0 :(得分:3)
周围有很好的博客文章,谈论这个非常具体的话题。我将简要介绍如何以及从何处开始。
我将约翰·阿滕斯的例子提到reference。
由于您已经拥有User
类,因此可以直接进入AccountController并实现索引方法。您希望首先显示所有用户,以便选择要删除的用户。
[Authorize(Roles = "Admin")]
public ActionResult Index()
{
var Db = new ApplicationDbContext();
var users = Db.Users;
//ViewModel will be posted at the end of the answer
var model = new List<EditUserViewModel>();
foreach(var user in users)
{
var u = new EditUserViewModel(user);
model.Add(u);
}
return View(model);
}
从那里你可以实现删除方法(GET和POST):
[Authorize(Roles = "Admin")]
public ActionResult Delete(string id = null)
{
var Db = new ApplicationDbContext();
var user = Db.Users.First(u => u.UserName == id);
var model = new EditUserViewModel(user);
if (user == null)
{
return HttpNotFound();
}
return View(model);
}
[HttpPost, ActionName("Delete")]
[ValidateAntiForgeryToken]
[Authorize(Roles = "Admin")]
public ActionResult DeleteConfirmed(string id)
{
var Db = new ApplicationDbContext();
var user = Db.Users.First(u => u.UserName == id);
Db.Users.Remove(user);
Db.SaveChanges();
return RedirectToAction("Index");
}
EditUserViewModel
public class EditUserViewModel
{
public EditUserViewModel() { }
// Allow Initialization with an instance of ApplicationUser:
public EditUserViewModel(ApplicationUser user)
{
this.UserName = user.UserName;
this.FirstName = user.FirstName;
this.LastName = user.LastName;
this.Email = user.Email;
}
[Required]
[Display(Name = "User Name")]
public string UserName { get; set; }
[Required]
[Display(Name = "First Name")]
public string FirstName { get; set; }
[Required]
[Display(Name = "Last Name")]
public string LastName { get; set; }
[Required]
public string Email { get; set; }
//you might want to implement jobs too, if you want to display them in your index view
}
*刚刚:这不是我自己的代码。这是John Atten在http://typecastexception.com撰写的一个例子。 *