如何自动添加一对多对象

本文关键字:多对象 添加 何自动 | 更新日期: 2023-09-27 17:51:08

我是ASP的新手。. NET MVC和我有问题,试图插入一个对象1xn自动使用我的方法创建。我想知道如何插入RelUserHomes对象,我需要homeId,但它只存在于db.SaveChanges()之后。

下面是一个片段:

<<h3>控制器房屋/h3>
[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);
}

模型RelUserHomes

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; }
}
应用DBContext

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; }
}

如何自动添加一对多对象

如果RelUserHomes实体具有指向Home实体的外键关系,则必须首先将Home对象添加到数据库中,以便为其分配HomeId值。您可以简单地在代码的前面添加一个db.SaveChanges(),然后将Home.

HomeId属性赋给relUserHomes

尝试将您的代码更改为以下内容:

[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);
}