如何引用然后将数据插入到数据库中自动创建的关联实体中?

How to reference and then insert data into associative entity that is created automatically in db?

我是 Entity Framework 的新手。

我使用 Code First 方法创建了 tables 并且它有效,即创建了 Users、Phones、UsersPhones tables。

现在我可以将数据添加到 Phones table 和 Users table 因为它们在我的实体模型中被提及但是我如何将数据插入我没有数据实体的 UsersPhones 关联实体或模型,因为它是自动创建的。

代码:

手机:

 public class Phones
    {
        public int ID { get; set; }
        public string Model { get; set; }
        public string Manufacturer { get; set; }
        public List<Users> Users { get; set; }
    }

用户:

 public class Users
    {
        public int ID { get; set; }
        public string Name { get; set; }
        public List<Phones> Phones { get; set; }

    }

UsersPhonesDBContext

 public class UsersPhonesDBContext: DbContext
    {
        public DbSet<Users> Users { get; set; }
        public DbSet<Phones> Phones { get; set; }
    }

添加电话的控制器和操作:

        [HttpPost]
        public ActionResult Create(FormCollection fc)
        {
            Phones phone= new Phones();
            phone.Model= fc["Model"];
            phone.Manufacturer= fc["Manufacturer"];

            UsersPhonesDBContext.Phones.Add(phone);

            int r = UsersPhonesDBContext.SaveChanges();

            if (r > 0)
                return RedirectToAction("Index", "Test");
            else
                return Redirect("~Views/Shared/Error.cshtml");
        }

和用户以类似的方式。

但是 UsersPhones table 呢?

您正在添加没有用户的 phone 或没有 phone 的用户,那么关系 table UsersPhones 中没有数据。

如果你想在这个 table 中有数据,那么你必须将用户与 phone 相关联:例如:

[HttpPost]
public ActionResult CreateUserWithPhone(FormCollection fc)
{
    ...
    using (var context = new UsersPhonesDBContext())
    {
        var user= new Users { Name = "testName" };
        context.Users.Add(user);

        var phone = new Phones{ Model= "testModel" };
        context.Phones.Add(phone);

        user.Phones = new List<Phones>();
        user.Phones.Add(phone);

        context.SaveChanges();
    }
    ...
}

此代码将在用户 table 中创建一行,在电话 table 中创建一行,在用户电话 table 中创建一行。

--编辑--

我创建了一个控制台项目来测试它,使用您的 类(Phones、Users 和 UsersPhonesDBContext),这是 Program.cs:

class Program
{
    static void Main(string[] args)
    {
        using (var context = new UsersPhonesDBContext())
        {
            var user = new Users { Name = "testName" };
            context.Users.Add(user);

            var phone = new Phones { Model = "testModel" };
            context.Phones.Add(phone);

            user.Phones = new List<Phones>();
            user.Phones.Add(phone);

            context.SaveChanges();
        }
    }
}

执行程序后,它在 Users table、Phones table 和 UsersPhones table 中创建了一行: