2015-05-04 67 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

没问题。请标记我的答案是正确的,如果它解决了你的问题:) –