【问题标题】:best way to convert database table in codefirst to model首先将代码中的数据库表转换为模型的最佳方法
【发布时间】:2017-07-09 10:38:45
【问题描述】:

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

像这样:

我需要通过查看 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);
    }

它可以工作,但我需要使用最好的方式进行转换。

最好的方法是什么?

【问题讨论】:

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


【解决方案1】:

你可以使用这个 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);

【讨论】:

  • 你能帮我映射一下吗?
  • 现在我不行了
  • 你不会花太长时间的:))))
  • 伙计,我遇到了 automaper 的新问题。我在这篇文章或其他文章中提问???
  • Meaby in other with tag #automapper。如果我有空闲时间,我会尝试帮助
【解决方案2】:

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

在 Visual Studio 中转到 Project -> Add New Item… 从左侧菜单中选择数据,然后选择 ADO.NET 实体数据模型, 输入 BloggingContext 作为名称,然后单击 OK 这将启动实体数据模型向导 从数据库中选择 Code First 并单击 Next WizardOneCFE 选择与您在第一部分中创建的数据库的连接,然后单击下一步 WizardTwoCFE 单击表旁边的复选框以导入所有表,然后单击完成 WizardThreeCFE

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-11-01
    • 2018-03-13
    • 1970-01-01
    • 2016-09-28
    • 1970-01-01
    相关资源
    最近更新 更多