簡體   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