实体框架核心域和类

时间:2018-11-07 15:59:32

标签: c# asp.net-core entity-framework-core

我目前正在跟踪csharpfritz(microsoft)开发的项目。它被称为“ corewiki”。项目的某种形式的“维基百科”。 这是指向github上的存储库的链接:CoreWiki by Jeff Fritz 他在域类上发表评论:

我试图理解为什么他创建了一个实体 FromDomain 类和 ToDomain 类:

// Main model

public class CommentDAO
{
    public int Id { get; set; }
    public int ArticleId { get; set; }
    public virtual ArticleDAO Article { get; set; }
    public string DisplayName { get; set; }
    public string Email { get; set; }

    [NotMapped]
    public Instant Submitted { get; set; }
    public string Content { get; set; }
}


public static CommentDAO FromDomain(Core.Domain.Comment comment)
{
    return new CommentDAO
    {
        AuthorId = comment.AuthorId,
        Content = comment.Content,
        DisplayName = comment.DisplayName,
        Email = comment.Email,
        Id = comment.Id,
        ArticleId = comment.ArticleId,
        Submitted = comment.Submitted
    };
}

public Core.Domain.Comment ToDomain()
{
    return new Core.Domain.Comment
    {
        AuthorId = AuthorId,
        Content = Content,
        DisplayName = DisplayName,
        Email = Email,
        Id = Id,
        ArticleId = this.Article.Id,
        Submitted = Submitted
    };
}

1 个答案:

答案 0 :(得分:2)

那只是映射代码,以将域模型映射到数据访问对象,反之亦然。您可以通过多种方式来实现此目的,例如作者展示的方式,使用显式转换运算符或使用诸如AutoMapper之类的工具。

例如,请参阅Having the domain model separated from the persistence model(第一个Google命中“为什么将域模型与dao分开”),以解释您为什么想要这么做。