[英]EF Table-Per-Type: Add new child to an existing parent
我是ASP.NET MVC代碼的新手,首先,我實現了每個類型的表層次結構,如下所示:
public abstract class Request
{
public int RequestId {gets;set;}
public DateTime CreationDate {get;set;}
public string CreatedBy {gets;set;}
public bool Active {Get;set;}
}
public class RequestChildA : Request
{
public string RequestChildAProp1 {get;set;}
public string RequestChildAProp2 {get;set;}
...
}
public class RequestChildB : Request
{
public string RequestChildBProp1 {get;set;}
public string RequestChildBProp1 {get;set;}
...
}
Request table
+---------------+-------------------------+------------+--------+
| RequestId | CreationDate | CreatedBy | Active |
+---------------+-------------------------+------------+--------+
| 1 | 2019-08-19 09:40:39.817 | HydroFlask | 1 |
+---------------+-------------------------+------------+--------+
RequestChildA table
+---------------+-------------------------+---------------------+
| RequestId | RequestChildAProp1 | RequestChildAProp1 |
+---------------+-------------------------+---------------------+
| 1 | ValueA | ValueB |
+---------------+-------------------------+---------------------+
ChildA和ChildB可以共享同一請求。 我的問題是如何將NEW ChildB添加到也具有現有ChildA的現有請求中。
我嘗試了通常的方法:
var childB = new childB { RequestChildBProp1 = "Value1", RequestChildBPro2 = "Value2" };
childB.RequestId = 1;
db.RequestChildB.Add(childB);
db.SaveChanges();
它已完成,沒有錯誤,但是創建了一個新的請求。 我需要一個與現有ID相同的新ChildB。 請幫忙!
我的設計可能有誤,請耐心等待。 謝謝!
請嘗試以下未經測試的方法:
public class Request
{
public int RequestId {gets;set;}
public DateTime CreationDate {get;set;}
public string CreatedBy {gets;set;}
public bool Active {Get;set;}
}
public class RequestChildA
{
public string RequestChildAProp1 {get;set;}
public string RequestChildAProp2 {get;set;}
...
public virtual Request Request {get; set;}
}
public class RequestChildB
{
public string RequestChildBProp1 {get;set;}
public string RequestChildBProp1 {get;set;}
...
public virtual Request Request {get; set;}
}
我認為您需要像這樣創建RequestChildA
和RequestChildB
:
public class RequestChildB
{
public virtual Request Request {get;set;}
public string RequestChildBProp1 {get;set;}
public string RequestChildBProp1 {get;set;}
}
並像這樣插入數據:
db.RequestChildB.Add(new RequestChildB
{
Request = db.Request.Find(1),
//...other properties
});
db.SaveChanges();
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.