我正在写一个mvc 4 c#.net 4.5网站
我想创建一个新的公司对象并注册一个链接到该公司的新用户。
我的帐户模型是:
[Table("UserProfile")]
public class UserProfile
{
[Key]
[DatabaseGeneratedAttribute(DatabaseGeneratedOption.Identity)]
public int UserId { get; set; }
public string UserName { get; set; }
public string FirstName { get; set; }
public string LastName { get; set; }
public string EmailAddress { get; set; }
public string PhoneNumber { get; set; }
public bool MarketingEmailOptin { get; set; }
public bool isDisabled { get; set; }
public virtual Company CompanyICanEdit { get; set; }
}
如果我调用以下内容,则会将用户添加为罚款,但对于CompanyICanEdit字段为null:
WebSecurity.CreateUserAndAccount(addCompanyViewModel.User.UserName,
addCompanyViewModel.User.Password,
propertyValues: new
{
FirstName = addCompanyViewModel.User.FirstName,
LastName = addCompanyViewModel.User.LastName,
EmailAddress = addCompanyViewModel.User.EmailAddress,
PhoneNumber = addCompanyViewModel.User.PhoneNumber,
MarketingEmailOptin = addCompanyViewModel.User.MarketingEmailOptin,
isDisabled = false
});
我希望,因为我没有给它任何东西。
我尝试过添加(mycompany是公司对象):
WebSecurity.CreateUserAndAccount(addCompanyViewModel.User.UserName,
addCompanyViewModel.User.Password,
propertyValues: new
{
FirstName = addCompanyViewModel.User.FirstName,
LastName = addCompanyViewModel.User.LastName,
EmailAddress = addCompanyViewModel.User.EmailAddress,
PhoneNumber = addCompanyViewModel.User.PhoneNumber,
MarketingEmailOptin = addCompanyViewModel.User.MarketingEmailOptin,
isDisabled = false,
CompanyICanEdit = mycompany
});
但我收到错误消息,说它与该类型不匹配。
如何注册用户以使CompanyICanEdit包含mycompany的CompanyId值?
任何帮助将不胜感激。感谢
答案 0 :(得分:20)
如果有任何人遇到同样的问题,最终没有弄明白如何做到这一点,最后通过以下方式解决问题。
//
// POST: /BusinessManager/ManageCompanies/Add
[HttpPost]
public ActionResult Add(AddCompanyViewModel addCompanyViewModel)
{
if (ModelState.IsValid)
{
// Create company and attempt to register the user
try
{
WebSecurity.CreateUserAndAccount(addCompanyViewModel.User.UserName,
addCompanyViewModel.User.Password,
propertyValues: new
{
FirstName = addCompanyViewModel.User.FirstName,
LastName = addCompanyViewModel.User.LastName,
EmailAddress = addCompanyViewModel.User.EmailAddress,
PhoneNumber = addCompanyViewModel.User.PhoneNumber,
MarketingEmailOptin = addCompanyViewModel.User.MarketingEmailOptin,
isDisabled = false
});
db.Companies.Add(addCompanyViewModel.Company);
var newuser = db.UserProfiles.FirstOrDefault(u => u.UserName == addCompanyViewModel.User.UserName);
if (newuser != null)
{
newuser.CompanyICanEdit = addCompanyViewModel.Company;
db.Entry(newuser).State = EntityState.Modified;
db.SaveChanges();
return RedirectToAction("Index");
}
else
{
ModelState.AddModelError("", "New user wasn't added");
}
}
catch (MembershipCreateUserException e)
{
ModelState.AddModelError("", Mywebsite.Controllers.AccountController.ErrorCodeToString(e.StatusCode));
}
}
return View(addCompanyViewModel);
}