データベースを生成するために、MVC ASP.NETアプリケーションでcodefirst手法を使用しています。私は自分のテーブルの2つ、顧客とルームの間に1対1の関係を作成しようとしました。Entity Frameworkは、不要なレコードを1対多の関係で作成します
私は1人の顧客が1つ以上の部屋を予約できるようにしたいと思います。
後は、私の顧客のモデルである:
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オブジェクトを渡し、これまで、エンティティフレームワークでも新しいルームのレコードを作成するときのが言おうモデルであります関連する顧客エントリのルームIDを定義するとき。
のは、私は次のコードを実行しましょう、私は詳しく説明してみましょう:
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を持つ新しいレコードを作成します。どんな助け?
私は自分自身を知りたいと思っています! –
'Customer'オブジェクトの' Rooms'プロパティは 'virtual'でなければなりません。同様の回答を参照してくださいhttps://stackoverflow.com/questions/42411810/updating-child-objects-in-entity-framework-6/42412120#42412120 – Venky
バーチャルに設定しても全く違いはありません –