如何配置Entity Framework Core,使用Fluent API映射从两个表中获取数据的实体?

huangapple go评论51阅读模式
英文:

How to configure Entity Framework Core to map an entity that takes data from two tables with Fluent API?

问题

为了配置Entity Framework Core,我使用Fluent API。我想知道是否有一种方法可以映射一个实体,其中一些属性与一个表相关,而另一些属性与另一个表相关。

这仅用于查询目的,以便在一个实体中获得联接的结果。在我的情况下,我有以下实体:

class Document
{
    long Id,
    string Name,
    long IdUserLastModification,
    string UserNameLastModification,
    DateTime DateLastModification,
}

在我的数据库中,有两个表:

  • Document(IdDocument,Name,IdUserLastModification,DateLastModification)
  • User(IdUser,Name,Surname,UserName)

在T-SQL中,我会这样做:

select 
    IdDocument, Name, IdUser, Surname, DateLastModification 
from 
    Documents as d
inner join 
    User as u on u.IdUser = d.IdUserLastModification

谢谢!

英文:

To configure Entity Framework Core, I use the Fluent API. I would like to know if there is some way to map an entity that has some properties related with a table and another properties with another.

It is just for query purposes, to have in one entity the result of the join. In my case I have this entities:

class Document
{
   long Id,
   string Name,
   long IdUserLastModification,
   string UserNameLastModification,
   DateTime DateLastModification,
}

In my database I have two tables:

  • Document (IdDocument, Name, IdUserLastModification, DateLastModification)
  • User (IdUser, Name, Surname, UserName)

In T-SQL I would do in like this:

select 
    IdDocument, Name, IdUser, Surname, DateLastModification 
from 
    Documents as d
inner join 
    User as u on u.IdUser = d.IdUserLastModification

Thanks so much.

答案1

得分: 1

我不确定你的意思,但你可以在实体类中添加扩展方法和字段,根据用户ID返回经过筛选的文档列表(以下是未经测试的伪代码),并将用户名作为文档实体的一部分包括。

public partial class Documents //假设这是DbSet
{
    public List<Document> GetDocumentsLastModified(long UserID)
    {
        var result = from d in dbContext.Documents
                     join u in Users on d.IdUserLastModification equals u.IdUser
                     where u.IdUser == UserID
                     select new
                     {
                         UserName = u.UserName,
                         Document = d
                     };
        return result.ToList();
    }

    [NotMapped] // 这会使EF Core生成的SQL忽略此字段,否则它将包括在所有文档查询中
    public string UserName { get; set; } //如果包括了导航属性,可以在getter中执行一些逻辑,如其他人所解释的
}

希望这有所帮助。

英文:

I'm not exactly sure what you mean, but you can add an extension method and field to your entity class to return the filtered document list based on a user id (untested pseudo code follows) and include the UserName as part of your document entity.

public partial class Documents //Assuming this is the DbSet
{
    public List&lt;Document&gt; GetDocumentsLastModified(long UserID)
    {
         var result = from d in dbContext.Documents
                 join User as u on d.IdUserLastModification equals u.IdUser
                 select u.UserName, d.*
                 where u.IdUser == UserID;
         return result.ToList();
     }
     [NotMapped] // this keeps the sql generated by EF core to ignore this field otherwise it would include as part of all Document queries
     public string UserName {get; set;} //you could do some of the logic in getter if you include the navigation as explained by others
}

答案2

得分: 0

如果您有一个 dbcontext,可以使用类似这样的代码(LINQ Join):

var result = (from ep in dbContext.Documents
              join u in dbContext.Documents on ep.IdUserLastModification equals u.IdUser
              select new {
                  UID = u.IdUser,
                  Name = ep.Name,
                  . . .
              });

如果没有,您始终可以执行像您在问题中所做的那样的 SQL 查询。

英文:

If you have a dbcontext you can use something like this (LINQ Join):

var result = (from ep in dbContext.Documents
                     join u in dbContext.Documents on ep.IdUserLastModification equals u.IdUser
                     select new {
                         UID = u.IdUser,
                         Name = ep.Name,
                         . . .
                     });

If you don't, you can always do an SQL query as you just did in the question.

答案3

得分: 0

以下是翻译好的部分:

你应该使用导航属性来设置你的类。

public class Document
{
    public long Id { get; set; }
    public string Name { get; set; }
    public long IdUserLastModification { get; set; }
    public string UserNameLastModification { get; set; }
    public DateTime DateLastModification { get; set; }

    public virtual User User { get; set; }
}

public class User
{
    public long IdUser { get; set; }
    public string Name { get; set; }
    public string Surname { get; set; }
    public string UserName { get; set; }

    public virtual ICollection<Document> Documents { get; } = new HashSet<Document>();
}

然后在你的 `DbContext` 中使用 Fluent API 配置关系:

modelBuilder.Entity<Document>(e =>
{
    e.HasKey(d => d.Id);

    e.HasOne(d => d.User)
        .WithMany(u => u.Documents)
        .HasForeignKey(d => d.IdUserLastModification);
});

然后,你可以使用匿名类型或 DTO 类来查询你想要的数据:

var documents = await dbContext.Documents
                .Select(d => new
                {
                    d.Id,
                    d.Name,
                    d.IdUserLastModification,
                    d.User.Surname,
                    d.DateLastModification
                })
                .ToListAsync();
英文:

You should setup your classes with Navigation properties.

public class Document
{
    public long Id{ get; set; }
    public string Name{ get; set; }
    public long IdUserLastModification{ get; set; }
    public string UserNameLastModification{ get; set; }
    public DateTime DateLastModification{ get; set; }

    public virtual User User { get; set; }
}

public class User
{
    public long IdUser { get; set; }
    public string Name { get; set; }
    public string Surname { get; set; }
    public string UserName { get; set; }

    public virtual ICollection&lt;Document&gt; Documents { get; } = new HashSet&lt;Document&gt;();
}

Then configure the relationship in your DbContext using fluent API:

modelBuilder.Entity&lt;Document&gt;(e =&gt;
{
    e.HasKey(d =&gt; d.Id);

    e.HasOne(d =&gt; d.User)
        .WithMany(u =&gt; u.Documents)
        .HasForeignKey(d =&gt; d.IdUserLastModification);
});

You can then query the data you want using either an anonymous type or a DTO class:

var documents = await dbContext.Documents
                .Select(d =&gt; new
                {
                    d.Id,
                    d.Name,
                    d.IdUserLastModification,
                    d.User.Surname,
                    d.DateLastModification
                })
                .ToListAsync();

huangapple
  • 本文由 发表于 2023年2月24日 00:09:12
  • 转载请务必保留本文链接:https://go.coder-hub.com/75547389.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定