2012-04-06 43 views
2

,我有以下數據模型:處理導航性能

enter image description here

我寫了需要支持添加新報告一個WCF服務:

public bool CreateNewReport(Report report) 
    { 
     MyEntities context = new MyEntities(); 
     context.AddToReports(Report); 
     context.SaveChanges(); 
    } 

所以我的方法得到一個在客戶端上生成的報表對象,並通過數據上下文將它添加到數據庫中。 (所有成員都包含在DataContract中)

我的問題是關於導航屬性。

  1. 客戶端是否還需要創建一個用戶對象並在發送之前將其放入新的報表對象中?
  2. 解決這個問題的最佳方法是什麼?我想到的一種方式是在插入新報表時在ReportEntity
  3. 中添加一個UserId字段,如何更新使用新報表的UserEntity Report導航屬性?

謝謝。

+1

一面注意:總是使用實體上下文,使用:'使用(var ctx = new MyEntities()){...}'。這將在使用塊的末尾調用Dispose,這將釋放所有使用的資源... – 2012-04-06 10:35:04

+0

@RicoSuter好點,謝謝 – Michael 2012-04-06 10:47:57

回答

1

如果導入數據庫,生成導航屬性(圖片中的屬性)和外部id屬性(例如,您在報表類中具有User和UserID屬性)。通過這種方式,您可以在客戶端中設置UserID並將其發送到服務器,並將其添加到AddToReports ...如果您發送整個用戶對象,則必須將其附加到實體環境,否則將再次創建用戶。 。

連接引用的用戶:(但最好只用ID發送用戶)

public bool CreateNewReport(Report report) 
{ 
    using (MyEntities context = new MyEntities()) 
    { 
     context.AddToReports(Report); 
     context.Users.Attach(report.User); 
     context.SaveChanges(); 
    } 
} 

要更改用戶的報告:

public bool ChangeUserToNewReport(int userid, Report newReport) 
{ 
    using (MyEntities context = new MyEntities()) 
    { 
     var user = context.Users.Single(u => u.ID = userid); 
     user.Report = newReport; 
     context.SaveChanges(); 
    } 
} 

現有報表:

public bool ChangeUserReport(int userid, Report existingReport) 
{ 
    using (MyEntities context = new MyEntities()) 
    { 
     context.Reports.Attach(existingReport); 
     var user = context.Users.Single(u => u.ID = userid); 
     user.Report = existingReport; 
     context.SaveChanges(); 
    } 
} 

這是您的模型應該是什麼樣子的示例。雙擊關聯線打開對話框。你可以看到PersonPersonID屬性是相同的。如果你像這樣創建你的模型,VS應該生成正確的SQL。 enter image description here

+0

謝謝,你介意我怎麼做,如果我有UserID外部id屬性在你建議的報告課上?我如何讓用戶表知道新的報告? – Michael 2012-04-06 11:01:21

+0

我不明白你的問題。我假設你的數據庫中已經有一個外鍵「ReportID」,從中導出了Report報道導航屬性。使用'ReportID'和'Report'屬性,你只有兩種方法來訪問這個外鍵(Report屬性支持延遲加載等等)。 – 2012-04-06 11:04:37

+0

對不起,因爲我是新手,而且我的數據庫知識不是這樣大。從我的理解你已經建議我應該添加另一個屬性到'ReportEntity'命名'UserId'(而不是'UserEntity'上的PK),並在創建新報表時更新它。這樣,我不需要創建一個用戶對象,並將其封裝在報表中,當我從客戶端發送它。正確嗎?除此之外,我與報告和用戶有一對多關係 – Michael 2012-04-06 11:10:00