She Knows
She Knows

Reputation: 25

convert one type to another in MVC

I have two references:

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

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

Upvotes: 0

Views: 1040

Answers (1)

hendrikdelarey
hendrikdelarey

Reputation: 452

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

Upvotes: 1

Related Questions