在MVC中将一种类型转换为另一种类型

时间:2022-09-24 19:00:17

I have two references:

我有两个参考:

  • in .Core reference I have one class with business functions.
  • in .Core参考我有一个具有业务功能的类。

  • in another one - models, views and controllers.
  • 在另一个 - 模型,视图和控制器。

I want to make a simple Crete function, but can not convert types.

我想制作一个简单的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 个解决方案

#1


You need to store your database entity and not you business object. You can convert your business model to your entity model as you write to it.. example below. At least this is what Im assuming you are trying to do.

您需要存储数据库实体而不是业务对象。您可以在写入时将业务模型转换为实体模型。下面的示例。至少这是我假设你要做的事情。

    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();
        }
    }

#1


You need to store your database entity and not you business object. You can convert your business model to your entity model as you write to it.. example below. At least this is what Im assuming you are trying to do.

您需要存储数据库实体而不是业务对象。您可以在写入时将业务模型转换为实体模型。下面的示例。至少这是我假设你要做的事情。

    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();
        }
    }