2016-06-30 12 views
0

In meiner Anwendung erstelle ich Identitätsrollen, möchte aber sicherstellen, dass ein Name desselben nicht existiert. Hier ist das, was ich habe versuchtWie überprüfe ich, ob eine Identity-Rolle existiert, bevor sie erstellt wird?

public ActionResult Create() 
{ 
    var Role = new IdentityRole(); 
    return View(Role); 
} 

[HttpPost] 
public ActionResult Create(IdentityRole Role) 
{ 
    var roleStore = new RoleStore<IdentityRole>(_context); 
    var roleManager = new RoleManager<IdentityRole>(roleStore); 
    if (!roleManager.RoleExists(Role.ToString())) 
    { 
     _context.Roles.Add(Role); 
     _context.SaveChanges(); //error points here 
     return RedirectToAction("Index"); 
    } 
    else 
    { 
     TempData["message"] = "This role already exists. Please check your roles and try again"; 
     return RedirectToAction("Index"); 
    } 

} 

Ich weiß, es Fehler, weil es ein Duplikat ist, da es funktioniert, wenn die Role anders, aber warum es nicht die if/else-Klausel scheint?

Antwort

1

Ihr Problem hier ist, dass Sie nicht den Rollennamen in die Exists Funktion sind vorbei, Sie Role.ToString() sind vorbei, die auf den Namen der Klasse aufgelöst wird, wahrscheinlich so etwas wie Microsoft.AspNet.Identity.EntityFramework.IdentityRole. Stattdessen sollten Sie Role.Name, wie folgt passieren:

if (!roleManager.RoleExists(Role.Name)) 
{ 
    _context.Roles.Add(Role); 
    _context.SaveChanges(); //error points here 
    return RedirectToAction("Index"); 
}