我试图实现的目标是,您拥有一个拥有多个玩家(ApplicationUsers)的团队,并且您拥有可能拥有许多团队的玩家(ApplicationUsers)。 (目前我只专注于指派一个团队)。
我在创建新用户时收到错误(在此问题的标题中)(代码如下)。成功创建新用户后,代码将调用:
CreateAsync(user, userViewModel.Password);
这是它失败的地方。
我收到的错误似乎与实体框架及其发送给SQL的指令有关(我在连接字符串中配置了本地SQL Express实例)。我已经搜索了StackOverflow这个错误,似乎有很多帖子,但我似乎无法找到与这种情况相关的答案 - 它们似乎都直接引用了SQL。不幸的是,我是.NET的新手,并且在EF和SQL方面很弱,这就是我伸出援手的原因。
我认为这个问题与EF试图在团队和ApplicationUsers之间建立的外键有关,这些外键给出了" IdentitySample.Models。 Team_Players "部分错误。
我正在使用.NET Identity 2.0示例项目,并为所包含的 ApplicationUser 类添加了一些其他属性,这些属性与我添加的新类有关," Team&#34 ;
public class ApplicationUser : IdentityUser
{
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 - db NOTE: Registration of claims from "IdentityExtensions.cs" class. See file.
// These need to be added to the ViewModels and the Controllers to capture the data. See the "AccountViewModel.cs"
// file, the "ManageViewModels.cs" and the "AccountController.cs" files, plus the views for corresponding changes.
userIdentity.AddClaim(new Claim("firstName", firstName));
userIdentity.AddClaim(new Claim("lastName", lastName));
userIdentity.AddClaim(new Claim("number", number.ToString()));
return userIdentity;
}
[Display(Name = "First Name")]
public string firstName { get; set; }
[Display(Name = "Last Name")]
public string lastName { get; set; }
[Display(Name = "Hawks Number")]
public int number { get; set; }
[Display(Name = "Successful Logins")]
public int successfulLogins { get; set; }
[Display(Name = "Password Status")]
public bool tempPassword { get; set; }
public virtual ICollection<Team> Teams { get; set; }
public ApplicationUser()
{
Teams = new List<Team>();
}
}
public class Team
{
public int Id { get; set; }
public string Name { get; set; }
public virtual ICollection<ApplicationUser> Players { get; set; }
public Team()
{
Players = new List<ApplicationUser>();
}
}
我有两个DbContexts,包括 ApplicationDbContext 以及我添加的一个 - IdentityDB - 它继承自ApplicationDbContext类。在IdentityDB上下文中,我添加了Team DbSet,&#34; Teams&#34;。
public class ApplicationDbContext : IdentityDbContext<ApplicationUser>
{
public ApplicationDbContext()
: base("DefaultConnection", throwIfV1Schema: false)
{
}
static ApplicationDbContext()
{
// Set the database intializer which is run once during application start
// This seeds the database with admin user credentials and admin role
Database.SetInitializer<ApplicationDbContext>(new ApplicationDbInitializer());
}
public static ApplicationDbContext Create()
{
return new ApplicationDbContext();
}
}
public class IdentityDB : ApplicationDbContext
{
public DbSet<Team> Teams { get; set; }
}
我通过创建名为RegistrationViewModel的视图模型的实例来创建用户:
public class RegisterViewModel
{
[Required]
[EmailAddress]
[Display(Name = "Email")]
public string Email { get; set; }
[Required]
[Display(Name = "First Name")]
public string firstName { get; set; }
[Required]
[Display(Name = "Last Name")]
public string lastName { get; set; }
[Display(Name = "Assigned Team")]
public string SelectedTeam { get; set; }
[Required]
[Display(Name = "Hawks Number")]
public int number { 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")]
[System.ComponentModel.DataAnnotations.Compare("Password", ErrorMessage= "The password and confirmation password do not match.")]
public string ConfirmPassword { get; set; }
public ICollection<SelectListItem> Teams { get; set; }
public RegisterViewModel()
{
Teams = new List<SelectListItem>();
}
}
UserAdminController中的:
//
// GET: /Users/Create
public async Task<ActionResult> Create()
{
//Get the list of Roles
ViewBag.RoleId = new SelectList(await RoleManager.Roles.ToListAsync(), "Name", "Name");
//Get list of Teams
IdentityDB _db = new IdentityDB();
var teams = _db.Teams.Select(t => new SelectListItem
{
Value = t.Name,
Text = t.Name
}).ToList();
return View(new RegisterViewModel { Teams = teams });
}
//
// POST: /Users/Create
[HttpPost]
public async Task<ActionResult> Create(RegisterViewModel userViewModel, params string[] selectedRoles)
{
IdentityDB _db = new IdentityDB();
Team userTeam = _db.Teams.First(x => x.Name == userViewModel.SelectedTeam);
if (ModelState.IsValid)
{
var user = new ApplicationUser
{
UserName = userViewModel.Email,
Email = userViewModel.Email,
firstName = userViewModel.firstName,
lastName = userViewModel.lastName,
number = userViewModel.number,
successfulLogins = 0,
tempPassword = true
};
user.Teams.Add(userTeam);
var adminresult = await UserManager.CreateAsync(user, userViewModel.Password); // CODE FAILS HERE
//Add User to the selected Roles
if (adminresult.Succeeded)
{
if (selectedRoles != null)
{
var result = await UserManager.AddToRolesAsync(user.Id, selectedRoles);
if (!result.Succeeded)
{
ModelState.AddModelError("", result.Errors.First());
ViewBag.RoleId = new SelectList(await RoleManager.Roles.ToListAsync(), "Name", "Name");
return View();
}
}
}
else
{
ModelState.AddModelError("", adminresult.Errors.First());
ViewBag.RoleId = new SelectList(RoleManager.Roles, "Name", "Name");
return View();
}
// Various email related activities that work fine and are unrelated to this error.
}
ViewBag.RoleId = new SelectList(RoleManager.Roles, "Name", "Name");
return View();
}
代码失败的CreateAsync方法的定义是:
[AsyncStateMachine(typeof(UserManager<,>.<CreateAsync>d__d))]
[DebuggerStepThrough]
public virtual Task<IdentityResult> CreateAsync(TUser user, string password);
SQL Express数据库确实包含一个名为&#34; ApplicationUserTeams&#34;的表。使用&#39; TeamId&#39;和&#39; ApplicationUser_Id&#39;创建的列,所以看起来EF正在完成它的工作,虽然有些事情在整个过程中失败。
此时进行故障排除的步骤包括删除整个数据库和项目中的迁移文件夹,然后再次运行应用程序,以便创建一个新的实例,以及一个新的&#34;初始&#34;移民。这对这个问题没有任何影响。我真的不知道从哪里去,所以任何帮助都将不胜感激。提前感谢您的时间。
编辑:为&#34;团队&#34;制作索引视图控制器,我注意到我收到错误&#39;无效的对象名称&#d; .ApplicationUserTeams&#39;。这是迭代外键属性&#34;玩家&#34;属于Application User类型。
@model IEnumerable<IdentitySamplesTEST.Models.Team>
@foreach (var item in Model) {
<tr>
<td>
@Html.DisplayFor(modelItem => item.Name)
</td>
@if (item.Players.Count == 0) @*ERROR OCCURS HERE*@
{
<td>
None.
</td>
}
else
{
foreach (var player in item.Players)
{
<td>
@Html.DisplayFor(modelItem => player.firstName)
</td>
}
}
数据库中的表实际上称为 dbo.TeamApplicationUsers - 向后看似EF正在寻找的内容。我不知道会导致什么......