将codefirst中的数据库表转换为模型的最佳方法

时间:2017-02-20 08:29:05

标签: c# asp.net asp.net-mvc asp.net-mvc-4 c#-4.0

我有新闻表,我需要转换为模型。

像这样:

我需要通过查看NewsModel,我有表News

我将其转换为:

 public ActionResult EditNews(int NewsID)
    {
        NewsModel model = new NewsModel();
        var editservice = _NewsSerivce.NewsByID(NewsID);
        model.NewsID = editservice.NewsID;
        model.NewsHeader = editservice.NewsHeader;
        model.NewsTitle = editservice.NewsTitle;
        model.NewsText = editservice.NewsText;
        model.NewsDefaultFile = editservice.NewsDefaultFile;
        model.CatID = editservice.CatID;
        model.SubCatID = editservice.SubCatID;
        DropDownCategory(model);
        return View("Edit",model);
    }

它有效,但我需要使用最好的转换方式。

最好的方法是什么?

2 个答案:

答案 0 :(得分:2)

你可以使用这个nuget: http://automapper.org/

文档在这里: https://github.com/AutoMapper/AutoMapper/wiki/Getting-started

我不知道你的班级是怎样的,所以我上课了:

  public  class TestClass
{
    public int NewsID { get; set; }
    public string NewsHeader { get; set; }
    public string NewsTitle { get; set; }
    public string NewsText { get; set; }
    public string NewsDefaultFile { get; set; }
    public int CatID { get; set; }
    public int SubCatID { get; set; }
}

和我的映射类:

   public class NewTestClass
{
    public int NewsID { get; set; }
    public string NewsHeader { get; set; }
    public string NewsTitle { get; set; }
    public string NewsText { get; set; }
    public string NewsDefaultFile { get; set; }
    public int CatID { get; set; }
    public int SubCatID { get; set; }
}

我已经像这样映射了这个类:

 TestClass tc = new TestClass { CatID = 1, NewsID = 1, SubCatID = 1, NewsDefaultFile = "test1", NewsHeader = "test2", NewsText = "test3", NewsTitle = "test4" };

        Mapper.Initialize(cfg => cfg.CreateMap<TestClass, NewTestClass>());
        var config = new MapperConfiguration(cfg => cfg.CreateMap<TestClass, NewTestClass>());

        var mapper = new Mapper(config);

        NewTestClass ntx = Mapper.Map<NewTestClass>(tc);

        Console.WriteLine(ntx.NewsID);

答案 1 :(得分:-1)

在我看来,这个link是实体框架代码优先到现有数据库的最佳方法。

在visual studio中转到Project - &gt;添加新项目... 从左侧菜单中选择Data,然后选择ADO.NET Entity Data Model, 输入BloggingContext作为名称,然后单击“确定” 这将启动实体数据模型向导 从Database中选择Code First,然后单击Next WizardOneCFE 选择与您在第一部分中创建的数据库的连接,然后单击“下一步” WizardTwoCFE 单击Tables旁边的复选框以导入所有表,然后单击Finish WizardThreeCFE