Entity Framework 以一对多关系在数据库中创建不需要的记录

Entity Framework Creates Unwanted Records In Database in one to many relationships

我在我的 MVC ASP.NET 应用程序中使用代码优先技术来生成我的数据库。我试图在我的两个 table 客户和房间之间创建一对多关系。

我希望一位顾客能够预订一间或多间客房。

以下是我的客户模型:

public class Customer
{
    public int id { get; set; }

    [Display(Name = "Name")]
    public string name { get; set; }

    [Display(Name = "Email Address")]
    public string email { get; set; }

    [Display(Name = "Phone Number")]
    public string phoneno { get; set; }

    [Display(Name = "Date of Birth")]
    public DateTime DOB { get; set; }

    [Display(Name = "CNIC")]
    public string cnic { get; set; }

    public List<int> Roomsid { get; set; }


    [Display(Name = "Check In Date")]
    public DateTime? checkin { get; set; }

    [Display(Name = "Check Out Date")]
    public DateTime? checkout { get; set; }

    public List<Room> Room { get; set; }
}

下面是型号

    public class Room
{
    public int id { get; set; }

    public int floorno { get; set; }

    public string roomclass { get; set; }

    public int cost { get; set; }

    public string bedcount { get; set; }

    public string facilities { get; set; }

    public string description { get; set; }

    public int? Customerid { get; set; }

}

假设每当我将 Customer 对象传递到我的数据库时,即使我为相关客户条目定义了 RoomID,实体框架也会创建新的 Room 记录。

让我详细说明一下,假设我 运行 以下代码:

ApplicationDbContext x = new ApplicationDbContext();
        var a = new Customer() { };
        var b = new List<Room>() {
            new Room { id=2 ,floorno=2, bedcount="2", cost=2, description="2", facilities="2", roomclass="2" },
            new Room {id=3 ,floorno=3, bedcount="3", cost=2, description="3", facilities="3", roomclass="3" },
            new Room {id=4 ,floorno=4, bedcount="4", cost=4, description="4", facilities="4", roomclass="4" },
        };


        a.checkin = Convert.ToDateTime("05 Mar 2017");
        a.checkout = Convert.ToDateTime("07 Mar 2017");
        a.DOB = Convert.ToDateTime("02 Mar 2000");
        a.cnic = "asfsgwlkgnwe98hf0";
        a.email = "agjw98e98weg98";
        a.name = "Äfnan Makhdoom";
        a.Rooms = b;

        x.Customers.Add(a);
        x.SaveChanges();

或者即使我没有在我的变量 b 中定义除房间 ID 之外的任何其他参数,我也会在我的数据库中的房间 table 中创建额外的记录。

即使我选择 RoomID 为 1,它也会使用新的 RoomID 创建一个新记录,其他字段与我定义的相同。有帮助吗?

如果您只想将客户添加到现有房间,您可以这样做。

    var a = new Customer() { };
    var roomWithId3 = x.Rooms.Single(x => x.Id == 3);

   a.rooms.Add(roomWithId3);
    x.Customers.Add(a);
    x.SaveChanges();