C# 尝试使用entityframework MVC将数据插入数据库时发生InvalidoPreration异常

C# 尝试使用entityframework MVC将数据插入数据库时发生InvalidoPreration异常,c#,asp.net-mvc,entity-framework,C#,Asp.net Mvc,Entity Framework,我的数据库中有两个表, 1.雇员,模型如下 public class Employees { public int Id { get; set; } public string FirstName { get; set; } public string LastName { get; set; } public int DepartmentId { get; set; } public string Designation { get; set; }

我的数据库中有两个表, 1.雇员,模型如下

public class Employees
{
    public int Id { get; set; }
    public string FirstName { get; set; }
    public string LastName { get; set; }
    public int DepartmentId { get; set; }
    public string Designation { get; set; }
    public DateTime DateOfBirth { get; set; }
    [ForeignKey("Id")]
    public virtual IList<Address> Address { get; set; }
}
员工可以有多个地址。我正在动态添加用于添加地址的控件。我正在使用Entityframe进行所有操作,如创建数据库、更新等

我用于将数据添加到数据库的代码如下所示

[HttpPost]
    [ValidateAntiForgeryToken]
    public ActionResult Create(string command,[Bind(Include = "Id,FirstName,LastName,DepartmentId,Designation,DateOfBirth")] Employees employees, [Bind(Include = "Id,AddressLine1,AddressLine2,City,State,PinCode")] List<Address> address)
    {
            if (ModelState.IsValid)
            {
                foreach (var item in address)
                {
                    db.Address.Add(item);
                }
                db.Employees.Add(employees);
                db.SaveChanges();
                return RedirectToAction("Index");
            }
            return View(employees);
    }
当我插入数据时,数据被插入到数据库中,但我得到以下异常

EntityFramework.SqlServer.dll中发生“System.InvalidOperationException”类型的异常,但未在用户代码中处理

其他信息:已成功提交对数据库的更改,但更新对象上下文时出错。ObjectContext可能处于不一致的状态。内部异常消息:无法在实体类型GridSample.Models.Employees上设置字段/属性地址。有关详细信息,请参见InnerException

内部异常:

{无法将“GridSample.Models.Address”类型的对象强制转换为“System.Collections.Generic.IList`1[GridSample.Models.Address]”类型。}

请帮我解决这个问题。

我认为不能在一对多关系中的一个类中的属性上使用ForeignKeyAttribute。应该在多类中的属性上使用它来指定一个类实例的键。因此,在您的情况下,您应该修改实体类以反映这种关系

public class Employees
{
    //...

    [InverseProperty("Employee")]
    public virtual ICollection<Address> Addresses { get; set; }
}

public class Address
{
    //...

    public int EmployeeId { get; set; }

    [ForeignKey("EmployeeId"), InverseProperty("Addresses")]
    public virtual Employees Employee { get; set; }
}
编辑

您没有获得任何地址的原因是,您将员工和地址单独添加到数据库中,也就是说,没有指示它们之间的关系。有几种方法可以做到这一点,我认为最简单的方法是利用导航属性:

I:将地址添加到员工的地址集合,而不是直接添加到数据库集:

foreach (var item in address)
{
    employees.Addresses.Add(item);
}
db.Employees.Add(employees);
db.SaveChanges();
或II:对于每个地址,指定其所属的员工:

foreach (var item in address)
{
    item.Employee = employees;
    db.Address.Add(item);
}
db.Employees.Add(employees);
db.SaveChanges();

这不管用。我现在没有在地址中获取值。对我来说,地址是空的。
foreach (var item in address)
{
    employees.Addresses.Add(item);
}
db.Employees.Add(employees);
db.SaveChanges();
foreach (var item in address)
{
    item.Employee = employees;
    db.Address.Add(item);
}
db.Employees.Add(employees);
db.SaveChanges();