2009-06-01 27 views
0

我曾與LINQ to SQL的一個工作頁面,現在我目前將其轉換爲LINQ到實體如何從一個視圖傳遞一個的EntityKey(參考)控制器

我的測試項目包含2個表,接觸(ID,名稱,電子郵件)和評論(編號,contactid,評論)

當我想創建一個新的評論,我把視圖放在隱藏字段contactid,它提交與提交的一切按鈕

它與linq2sql正常工作,但它不適用於linq2entity

如何用linq2entity做到這一點?

編輯#1

實際上的問題是,我該如何處理與一個或多個外鍵

?在那種情況下,我只有一個,是的,我可以使用eu-ge-ne的建議,但如果我得到第二個呢?

編輯#2

found this解決方案現在

回答

1

這是更好地提供的ContactID作爲URL的一部分。例如(與 「默認」 路線):

public CommentController : Controller 
{ 
    [AcceptVerbs(HttpVerbs.Post)] 
    public ActionResult Add(int id) 
    { 
     ... 
    } 
} 

在你看來:

<% using (Html.BeginForm(new { 
    controller = "comment", 
    action = "add", 
    id = /* commentId from your Model */ })) { %> 
    ... 
<% } %> 

更新:

如果你有2個或更多的外鍵:

S1:

routes.MapRoute("CustomRoute", "{controller}/{action}/{id1}/{id2}", 
    new { controller = "home", action = "index", id1 = "", id2 = "" }); 

... 

[AcceptVerbs(HttpVerbs.Post)] 
public ActionResult Add(int id1, int id2) 
{ 
    ... 
} 

... 

<% using (Html.BeginForm(new { 
    controller = "comment", 
    action = "add", 
    id1 = /* foreighn key 1 */, 
    id2 = /* foreighn key 2 */ })) { %> 
    ... 
<% } %> 

S2:

在查看:

<% using (Html.BeginForm(new { controller = "comment", action = "add" })) { %> 
    ... 

    <input id="foreignKeyId1" type="hidden" value="<%= /* foreign key 1 */ %>" /> 
    <input id="foreignKeyId2" type="hidden" value="<%= /* foreign key 2 */ %>" /> 
    ... 
    <input id="foreignKeyIdN" type="hidden" value="<%= /* foreign key N */ %>" /> 
<% } %> 

[AcceptVerbs(HttpVerbs.Post)] 
public ActionResult Add(FormCollection form) 
{ 
    var foreignKey1 = form["foreignKeyId1"] 
    var foreignKey2 = form["foreignKeyId2"] 
    ... 
    var foreignKeyN = form["foreignKeyIdN"] 

    ... 
} 
+0

看看我的編輯在原來的職位,如果我只有1個外鍵,但如果我有一個以上的好主意嗎? – Fredou 2009-06-01 23:08:51

相關問題