我当然是在深水中,虽然我一直在寻找许多“类似”的帖子,但我似乎无法想象这一点。
我正在尝试与“公司模型”和ApplicationUser建立连接。 该公司拥有许多AU,AU可以拥有许多公司。虽然当我创建一个公司并从selectList中选择不同的用户时(我检查过,确实传递了AU-ID。
警告:我只是一个菜鸟,我在跟踪指南时遇到了很多问题,但是没有 - 所以可能会有明显的错误。
模特公司:
public Company()
{
this.Users = new List<ApplicationUser>();
}
public int ID { get; set; }
public string Name { get; set; }
public string Address { get; set; }
public string Zip { get; set; }
public string City { get; set; }
public string Cvr { get; set; }
public string Telephone { get; set; }
public string Email { get; set; }
public string Website { get; set; }
public string BillingEmail { get; set; }
[ForeignKey("UserId")]
public List<string> UserId { get; set; }
public virtual List<ApplicationUser> Users { get; set; }
}
模型ApplicationUser
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
userIdentity.AddClaim(new Claim("FirstName", this.FirstName.ToString()));
userIdentity.AddClaim(new Claim("LastName", this.LastName.ToString()));
return userIdentity;
}
public ApplicationUser()
{
this.Companies = new List<Company>();
}
public string FirstName { get; set; }
public string LastName { get; set; }
public virtual List<Company> Companies { get; set; }
}
控制器
[HttpPost]
public async Task<ActionResult> CreateCompany(CreateCompanyViewModel model)
{
if (ModelState.IsValid)
{
DAL.CompanyContext context = new DAL.CompanyContext();
// Creating object from recieved form
DomainModels.Company newCompany = new DomainModels.Company();
newCompany.Address = model.Address;
newCompany.BillingEmail = model.BillingEmail;
newCompany.City = model.City;
newCompany.Cvr = model.Cvr;
newCompany.Email = model.Email;
newCompany.Name = model.Name;
newCompany.Telephone = model.Telephone;
newCompany.Website = model.Website;
newCompany.Zip = model.Zip;
newCompany.UserId = model.SelectedApplicationUserId;
// adding and saving
context.Companies.Add(newCompany);
await context.SaveChangesAsync();
return RedirectToAction("Index");
}
return View(model);
}
的DbContext
public DbSet<Company> Companies { get; set; }
protected override void OnModelCreating(DbModelBuilder mb)
{
base.OnModelCreating(mb);
mb.Entity<Company>()
.HasMany(c => c.Users)
.WithMany(d =>d.Companies)
.Map(m=>
{
m.MapLeftKey("Company_ID");
m.MapRightKey("ApplicationUser_Id");
m.ToTable("CompanyApplicationUsers");
});
}
}
我真的很困惑。搜索谷歌,我发现很多帖子表明我需要创建一个OnModelCreate,虽然我认为EF会自动执行此操作 - 请注意,它自动创建了一个表,其中包含“CompanyApplicationUsers”表(这就是我使用这些信息的原因) )。
每次都会创建公司,但没有任何内容发布到关系表中。
我有一种感觉,我在这里乱搞 - 我希望我会学习! :)
感谢您的帮助。
更新1:
我更改了模型,而是指向ApplicationUser(Users)作为外键。我遍历我从视图中收到的ID列表,并创建一个用户并将这些添加到newCompany List ..
然而,虽然我不确定这是否正确,但我还在Context.savechanges上收到验证错误“一个或多个实体的验证失败”
此处的错误与我创建的用户填写列表有关 - 它们需要一些其他信息,例如用户名。请注意,我只想要关系,而不是创建实际用户。
[HttpPost]
public async Task<ActionResult> CreateCompany(CreateCompanyViewModel model)
{
if (ModelState.IsValid)
{
DAL.CompanyContext context = new DAL.CompanyContext();
// Creating object from recieved form
DomainModels.Company newCompany = new DomainModels.Company();
newCompany.Address = model.Address;
newCompany.BillingEmail = model.BillingEmail;
newCompany.City = model.City;
newCompany.Cvr = model.Cvr;
newCompany.Email = model.Email;
newCompany.Name = model.Name;
newCompany.Telephone = model.Telephone;
newCompany.Website = model.Website;
newCompany.Zip = model.Zip;
foreach (string i in model.SelectedApplicationUserId)
{
ApplicationUser user = new ApplicationUser();
user.Id = i;
newCompany.Users.Add(user);
}
//newCompany.Users = model.SelectedApplicationUserId;
// adding and saving
context.Companies.Add(newCompany);
await context.SaveChangesAsync();
return RedirectToAction("Index");
}
return View(model);
}
更新2
现在生病与1对多关系,我可以工作。在这种情况下,我只需使用每个关联用户的CompanyID更新ApplicationUser。 我仍然想知道如何创建多对多,也许是我在这里做的一些,也是需要的。但我无法弄明白。
//newCompany.Users = model.SelectedApplicationUserId;
// adding and saving
context.Companies.Add(newCompany);
try
{
int response = await context.SaveChangesAsync();
}
catch(Exception exception)
{
}
foreach (string i in model.SelectedApplicationUserId)
{
var user = await UserManager.FindByIdAsync(i);
user.CompanyId = newCompany.ID;
IdentityResult result = await UserManager.UpdateAsync(user);
}
try
{
}
catch (Exception exception)
{
throw;
}
return RedirectToAction("Index");
}
return View(model);
答案 0 :(得分:1)
您应该可以使用正确配置的类执行类似的操作:
var userList = new List<ApplicationUser>();
foreach (string i in model.SelectedApplicationUserIds)
{
userList.Add(new ApplicationUser {Id = i});
}
var newCompany = new Company
{
Address = model.Address;
BillingEmail = model.BillingEmail;
City = model.City;
// etc.
Users = userList
};
int response = await context.SaveChangesAsync();
EF会自动建立联系。请注意,您不需要使用UserManager来检索用户 - 它可以从context.Users。
获得