繁体   English   中英

实体框架以一对多关系在数据库中创建不需要的记录

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

我在MVC ASP.NET应用程序中使用Codefirst技术生成数据库。 我试图在两个表“客户”和“房间”之间创建一对多关系。

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

以下是我的客户模型:

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

}

假设当我将客户对象传递到数据库时,即使我为相关客户条目定义了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以外的任何其他参数,我也会在数据库的“房间”表中创建其他记录。

即使将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();

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM