我是ASP.NET MVC的新手,我在尝试插入对象时遇到问题1xn自动使用我的方法Create。我想知道如何插入对象RelUserHomes,我需要homeId,但它只存在于db.SaveChanges()之后。
这是一个片段:
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult Create([Bind(Include = "HomeId,Name")] Home home)
{
if (ModelState.IsValid)
{
db.Homes.Add(home);
RelUserHomes relUserHomes = new RelUserHomes();
// I did this because I need the homeId to insert this object
relUserHomes.HomeId = db.SaveChanges();
relUserHomes.Email = Session["Email"].ToString();
relUserHomes.IsAdmin = true;
db.RelUserHomes.Add(relUserHomes);
db.SaveChanges();
}
return View(home);
}
public class RelUserHomes
{
[Key]
public int RelUserHomesId { get; set; }
public bool IsAdmin { get; set; }
[Required]
public string Email { get; set; }
[Required]
public int HomeId { get; set; }
[Key]
public Home Homes { get; set; }
}
public class ApplicationDbContext : IdentityDbContext<ApplicationUser>
{
public ApplicationDbContext() : base("PrimoEntities")
{
}
public override int SaveChanges()
{
try
{
return base.SaveChanges();
}
catch (DbEntityValidationException ex)
{
// Retrieve the error messages as a list of strings.
var errorMessages = ex.EntityValidationErrors.SelectMany(x => x.ValidationErrors).Select(x => x.ErrorMessage);
var fullErrorMessage = string.Join("; ", errorMessages);
var exceptionMessage = string.Concat(ex.Message, " The validation errors are: ", fullErrorMessage);
// Throw a new DbEntityValidationException with the improved exception message.
throw new DbEntityValidationException(exceptionMessage, ex.EntityValidationErrors);
}
}
public DbSet<Home> Homes { get; set; }
public DbSet<RelUserHomes> RelUserHomes { get; set; }
}
答案 0 :(得分:2)
如果RelUserHomes
实体具有指向Home
实体的外键关系,则必须首先将Home
对象添加到数据库,以便为其分配{{1价值。您只需在代码中稍早添加HomeId
,然后分配db.SaveChanges()
relUserHomes
HomeId
属性Home.
尝试将代码更改为以下内容:
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult Create([Bind(Include = "HomeId,Name")] Home home)
{
if (ModelState.IsValid)
{
db.Homes.Add(home);
db.SaveChanges();
RelUserHomes relUserHomes = new RelUserHomes();
relUserHomes.HomeId = home.HomeId;
db.RelUserHomes.Add(relUserHomes);
db.SaveChanges();
}
return View(home);
}