【发布时间】:2018-08-14 19:34:56
【问题描述】:
到目前为止,我一直使用自己的 DAL for SQL Server。 在一个新项目中,我决定在 MVC 项目和 Identity 中使用 Entity。 我曾经使用桥接表。 这是我的 IdentityModels(简化版)
应用程序用户
public class ApplicationUser : IdentityUser
{
[Required]
public string Surname { get; set; }
[Required]
public string Name { get; set; }
public virtual ICollection<Group> Groups { get; set; }
}
组
public class Group
{
[Key]
public int Id { get; set; }
[Display(Name = "Nom du Groupe")]
[Required]
[CustomRemoteValidation("IsGroupNameExist", "Groups", AdditionalFields =
"Id")]
public string Name { get; set; }
public virtual ICollection<ApplicationUser> ApplicationUsers { get; set;
}
和 DbContext
public class ApplicationDbContext : IdentityDbContext<ApplicationUser>
{
public ApplicationDbContext()
: base("DefaultConnection", throwIfV1Schema: false)
{
}
public static ApplicationDbContext Create()
{
return new ApplicationDbContext();
}
public DbSet<Group> Groups { get; set; }
}
我需要的所有表都已创建并且看起来创建良好(ApplicationUser Group 和 ApplicationUserGroups)。
问题是:
我有 3 个组(A、B、C),ID 为 1、2、3。我在ApplicationUser 表中添加了一个用户,Groups 属性中有 3 个组。
第一部分没问题,它在桥接表中添加了良好的值 (ApplicationUsersGroup) 但它再次添加了组 A、B、C,ID 为 4、5、6 在Group 表中。
UserManager 的CreateAsync 方法不是重点(仅Add 也是如此)。
如果我查看调试器,我可以看到当我将用户对象传递给 add 方法时,在 Groupsproperty 中,我有一个 ApplicationUsers 属性,在 Groups 属性内。对我来说,这可能是原因,但如果我从ApplicationUser 中删除Groups 属性,代码首先不会创建ApplicationUserGroups。
我错了,但是什么?如何在Grouptable 中没有额外条目的情况下拥有用户?
感谢您的帮助。
更新
好的,现在我明白了为什么要添加重复项,但就我而言,如何避免这种情况?
以下是Register 方法涉及的部分:
List<Group> selectedItems = new List<Group>();
foreach (GroupTableViewModel item in model.SelectedGroups)
{
if (item.Selected == true) selectedItems.Add(new Group { Id = item.Id, Name = item.GroupName });
}
var user = new ApplicationUser { Name = model.Name, Surname = model.Surname, UserName = model.Surname + "." + model.Name, Email = model.Email,Groups=selectedItems};
string password = RandomPassword.Generate(8, 8);
var result = await UserManager.CreateAsync(user, password);
CreateAsync() 是标识方法。我不明白它是如何添加用户的(我在 JustDecompile 中看不到任何 Add() 或 'SaveChanges())。
也许我又错了,但是如果我想将一个实体附加到上下文中,我必须创建一个新的上下文,这将不同于 CreateAsync() 方法使用的上下文。
所以需要帮助...
【问题讨论】:
-
一个用户将在多个组中?
-
是的,一个用户可以在多个组中,一个组可以有很多用户。
标签: c# entity-framework asp.net-identity