2015-05-04 59 views
0

我有兩個引用:轉換一個類型到另一個MVC

.Core參考
  • 我有業務功能一類。
  • 另一種 - 模型,視圖和控制器。

我想做一個簡單的Crete函數,但不能轉換類型。

//my model in .Core: 

public class A 
{ 
    public int id { get; set; } 
    public string name { get; set; } 
    public string address { get; set; } 
    public string phone { get; set; } 
} 

//my Business function in .Core: 

public void Add(A a) 
    { 
     using (My_Entities context = new My_Entities()) 
     { 
      context.tS.Add(a); 
      context.SaveChanges(); 
     } 
    } 



//My ViewModel: 

public class AViewModel 
{ 
    public int id { get; set; } 
    public string name { get; set; } 
    public string address { get; set; } 
    public string phone { get; set; } 
}enter code here 



//My controller: 

[HttpGet] 
    public ActionResult Add() 
    { 
     AViewModel d= new AViewModel(); 

     return PartialView("_Add", d); 
    } 

    [HttpPost] 
    public ActionResult Add(AViewModel a) 
    { 
     if (ModelState.IsValid) 
     { 
      ABusiness sb = new ABusiness(); 
      // sb.Add(a); 


      return RedirectToAction("List"); 
     } 


     return PartialView("_Add", a); 
    } 

回答

1

您需要存儲數據庫實體,而不是您的業務對象。您可以在寫入時將您的業務模型轉換爲實體模型。至少這是我假設你正在嘗試做的事情。

public void Add(A a) 
    { 
     using (My_Entities context = new My_Entities()) 
     { 
      context.tS.Add(new YourDatabaseEntity() 
       { 
        Id = a.id, 
        Name = a.name 
        // etc.. 
       }); 
      context.SaveChanges(); 
     } 
    } 
+0

我的問題是當我嘗試調用Add()函數時,我不知道如何傳遞A類型。我的意思是在我的控制器中我有AViewModel,但是在Business class function - public void Add(A a) –

+0

非常感謝,henk_vj,它的工作原理:) –

+0

沒問題。請標記我的答案是正確的,如果它解決了你的問題:) –

相關問題