Asp.net MVC'de çok yeniyim ve bu uygulamayı yapıyorum.Hata "INSERT deyimi, özel mülkiyet ve ilişki ile kimlik kullanarak FOREIGN KEY kısıtlaması ile çelişiyor"
Görsel stüdyo tarafından oluşturulan varsayılan IdentityModel.cs öğesine özel bir özellik eklemeye çalışıyorum. Bu customproperty, bir kullanıcının ait olduğu üniversite kütüphanesini düzenleyecektir.
Bu gönderiyi çok büyük yaptım, ancak sorunun nedenini ve gerçekten neyi ihmal etmem gerektiğini gerçekten bilmiyorum. Şimdiye kadar yapmış ne
: düzenlendi Üniversite kütüphanesi varlık:
public class UniversityLibrary
{
[Key]
public int UniversityLibraryId { get; set; }
public string UniversityLibraryName { get; set; }
public virtual ICollection<ApplicationUser> Users {get;set;}
}
Katma IdentityModel.cs için özel özellik:
public class ApplicationUser : IdentityUser
{
public virtual UniversityLibrary UniversityLibraries { get; set; }
public int UniversityLibraryId { get; set; }
public async Task<ClaimsIdentity> GenerateUserIdentityAsync(UserManager<ApplicationUser> manager)
{
// Note the authenticationType must match the one defined in CookieAuthenticationOptions.AuthenticationType
var userIdentity = await manager.CreateIdentityAsync(this, DefaultAuthenticationTypes.ApplicationCookie);
// Add custom user claims here
return userIdentity;
}
}
public class ApplicationDbContext : IdentityDbContext<ApplicationUser>
{
public ApplicationDbContext()
: base("name=DefaultConnection", throwIfV1Schema: false)
{
}
protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
base.OnModelCreating(modelBuilder);
}
public static ApplicationDbContext Create()
{
return new ApplicationDbContext();
}
}
Eklendi RegisterViewModel özel mülkiyet:
public class RegisterViewModel
{
[Required]
[EmailAddress]
[Display(Name = "Email")]
public string Email { get; set; }
[Required]
[DisplayName("University Library ID")]
public int UniversityLibraryId { get; set; }
public virtual ICollection<UniversityLibrary> Libraries { get; set; }
[Required]
[StringLength(100, ErrorMessage = "The {0} must be at least {2} characters long.", MinimumLength = 6)]
[DataType(DataType.Password)]
[Display(Name = "Password")]
public string Password { get; set; }
[DataType(DataType.Password)]
[Display(Name = "Confirm password")]
[Compare("Password", ErrorMessage = "The password and confirmation password do not match.")]
public string ConfirmPassword { get; set; }
}
University librarie s ActionFilter kullanarak Bence geçirilecek:
public class ViewbagListOfUniversityLibraries : ActionFilterAttribute
{
public override void OnActionExecuted(ActionExecutedContext filterContext)
{
IncludeRoleListIntoViewBag(filterContext.Controller.ViewBag);
base.OnActionExecuted(filterContext);
}
private void IncludeRoleListIntoViewBag(dynamic viewBag)
{
using (var db = new LibraryManagementWebAppContext())
{
viewBag.UniversityLibraryList = db.UniversityLibraries
.OrderBy(x => x.UniversityLibraryName)
.Select(unversityLibrary => new SelectListItem()
{
Text = unversityLibrary.UniversityLibraryName,
Value = unversityLibrary.UniversityLibraryId.ToString()
})
.ToList();
}
}
}
üniversite kütüphanelerinin açılan eklemek için Kayıt görünümü Modifiye:
@model LibraryManagementWebApp.Models.RegisterViewModel
@{
ViewBag.Title = "Register";
IEnumerable<SelectListItem> universityLibraryList = ViewBag.UniversityLibraryList;
}
...
<div class="form-group">
@Html.LabelFor(m => m.UniversityLibraryId, new { @class = "col-md-2 control-label" })
<div class="col-md-10">
@Html.DropDownListFor(m => m.UniversityLibraryId, universityLibraryList,"Select One", new { @class = "form-control" })
</div>
</div>
benim diğer bağlam (üniversite Kütüphaneleri için bağlam) için
Eklenen modelbuilders, "EntityType" IdentityUserLogin 'gibi anahtarlara neden olmadığı için hatalara neden olduğu için. ben yeni kayıt çalıştığınızda :
[HttpPost]
[AllowAnonymous]
[ViewbagListOfUniversityLibraries]
[ValidateAntiForgeryToken]
public async Task<ActionResult> Register(RegisterViewModel model)
{
if (ModelState.IsValid)
{
var user = new ApplicationUser { UserName = model.Email, Email = model.Email, UniversityLibraryId = Convert.ToInt32(model.UniversityLibraryId) };
var result = await UserManager.CreateAsync(user, model.Password);
if (result.Succeeded)
{
await SignInManager.SignInAsync(user, isPersistent:false, rememberBrowser:false);
// For more information on how to enable account confirmation and password reset please visit http://go.microsoft.com/fwlink/?LinkID=320771
// Send an email with this link
// string code = await UserManager.GenerateEmailConfirmationTokenAsync(user.Id);
// var callbackUrl = Url.Action("ConfirmEmail", "Account", new { userId = user.Id, code = code }, protocol: Request.Url.Scheme);
// await UserManager.SendEmailAsync(user.Id, "Confirm your account", "Please confirm your account by clicking <a href=\"" + callbackUrl + "\">here</a>");
return RedirectToAction("Index", "Home");
}
AddErrors(result);
}
// If we got this far, something failed, redisplay form
return View(model);
}
sorundur: my veritabanında yeni bir kullanıcı oluşturmadan önce seçilen değeri almak için denetleyici Modifiye bu EntityType"
public class LibraryManagementWebAppContext : DbContext
{
public LibraryManagementWebAppContext() : base("name=LibraryManagementWebAppContext")
{
}
public DbSet<UniversityLibrary> UniversityLibraries { get; set; }
protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
modelBuilder.Entity<IdentityUserLogin>().HasKey(l => l.UserId);
modelBuilder.Entity<IdentityRole>().HasKey(r => r.Id);
modelBuilder.Entity<IdentityUserRole>().HasKey(r => new { r.RoleId, r.UserId });
modelBuilder.Entity<UniversityLibrary>().HasKey(r => r.UniversityLibraryId);
base.OnModelCreating(modelBuilder);
}
}
anahtarı tanımlayın kullanıcı, bir bu hatayı alıyorum:
The INSERT statement conflicted with the FOREIGN KEY constraint "FK_dbo.AspNetUsers_dbo.UniversityLibraries_UniversityLibraryId". The conflict occurred in database "ASPNET_LIBRARYMANAGEMENTWEBAPP_aa38b17e20d0416d8c53a3a5d0faa59e", table "dbo.UniversityLibraries", column 'UniversityLibraryId'.
Ve bunu çözmek için nasıl bilmiyorum kodumu ayıklama benim kullanıcı değişkeni valu var görebilirsiniz. UniversityLibraryId için e. Debugging: user variable that is passed to CreateAsync
Ayrıca veritabanında da doğrulanmış ve UniversityLibrary tablosunda aynı kimliğe sahip öğe var. checked the database to see if the data is there