简体   繁体   English

Entity Framework Core 5 - 单一导航属性

[英]Entity Framework Core 5 - Single Navigation Property

I'm using Entity Framework Core 5 and I'm having problems retrieving records with all of their associated related data.我正在使用 Entity Framework Core 5,但在检索记录及其所有相关数据时遇到问题。 As you can see below, I have three classes;正如您在下面看到的,我有三个班级; Person, Client and ReferralPerson.个人、客户和推荐人。 Both Client and ReferralPerson contain Person objects and Client also contains a ReferralPerson object. Client 和 ReferralPerson 都包含 Person 对象,Client 还包含一个 ReferralPerson object。

public class Person
{
    public int ID { get; set; }

    [Required, StringLength(50)]
    public string FirstName { get; set; } = "N/A";

    [Required, StringLength(50)]
    public string LastName { get; set; } = "N/A";

    [StringLength(30)]
    public string PhoneNumberPrimary { get; set; }

    [StringLength(30)]
    public string PhoneNumberSecondary { get; set; }

    [StringLength(50)]
    public string Address { get; set; }

    [StringLength(50)]
    public string EmailAddress { get; set; }

}

public class Client
{
    public int ID { get; set; }
    public Person Person { get; set; }

    [StringLength(50)]
    public string CommunicationMethod { get; set; }
    public DateTime InitalContactDate { get; set; }       

    [Required, StringLength(100)]
    public string ReasonForVisit { get; set; }
    public ReferralPerson ReferralPerson { get; set; }

}

public class ReferralPerson
{
    public int ID { get; set; }
    public Person Person { get; set; }

    [StringLength(100)]
    public string BusinessName { get; set; }
    public int NumberOfReferrals { get; set; }

}

My OnModelCreating() method currently looks like the following:我的 OnModelCreating() 方法目前如下所示:

protected override void OnModelCreating(ModelBuilder modelBuilder)
{
    //setup our relationships
    modelBuilder.Entity<Client>()
        .HasOne(c => c.Person);

    modelBuilder.Entity<Client>()
        .HasOne(c => c.ReferralPerson);

    modelBuilder.Entity<Person>().ToTable("People");
    modelBuilder.Entity<ReferralPerson>().ToTable("ReferralContacts");

}

Finally, I have a method that's used for searching Client records as follows:最后,我有一个用于搜索客户端记录的方法,如下所示:

public IEnumerable<Client> GetClientsByLastName(string lastName)
{
    var query = db.Clients
                  .Include(x => x.Person)
                  .Include(x => x.ReferralPerson)
                  .Where(x => string.IsNullOrEmpty(lastName) || 
                    x.Person.LastName.Contains(lastName))
                  .ToList();

    return query;
}

Looking at the database tables that are created by the migration, I can see that the relationships appear to be correct between the Clients table, Person (People) table and ReferralContacts table.查看迁移创建的数据库表,我可以看到 Clients 表、Person (People) 表和 ReferralContacts 表之间的关系似乎是正确的。 I can also see that records are being added correctly to these tables when I save a new record.当我保存新记录时,我还可以看到记录被正确添加到这些表中。 The issue is with the retrieving.问题在于检索。 Even though I am using ".Include(x => x.Person)" in the "GetClientsByLastName()" method, the person object does not get populated when retrieving a Client record.即使我在“GetClientsByLastName()”方法中使用“.Include(x => x.Person)”,检索客户记录时也不会填充人员 object。 I've spent quite a bit of time looking at other posts and solutions as well as the EF Core documentation, but I'm still missing something.我花了很多时间查看其他帖子和解决方案以及 EF Core 文档,但我仍然遗漏了一些东西。 Any help would be greatly appreciated.任何帮助将不胜感激。

EDIT 5-9-2022:编辑 5-9-2022:

Here is the EF generated SQL query from the LINQ Query shown above这是 EF 从上面显示的 LINQ 查询生成的 SQL 查询

DECLARE @__lastName_0 nvarchar(50) = N'bur';
SELECT [c].[ID], 
[c].[CommunicationMethod], 
[c].[InitalContactDate], 
[c].[PersonID], 
[c].[ReasonForVisit],
[c].[ReferralPersonID],
[p].[ID],
[p].[Address],
[p].[EmailAddress],
[p].[FirstName],
[p].[LastName],
[p].[PhoneNumberPrimary],
[p].[PhoneNumberSecondary],
[r].[ID],
[r].[BusinessName],
[r].[NumberOfReferrals],
[r].[PersonID]
FROM [Clients] AS [c]
LEFT JOIN [People] AS [p] ON [c].[PersonID] = [p].[ID]
LEFT JOIN [ReferralContacts] AS [r] ON [c].[ReferralPersonID] = [r].[ID]
WHERE (@__lastName_0 LIKE N'') OR (CHARINDEX(@__lastName_0, [p].[LastName]) > 0)
ORDER BY [p].[LastName]

When I execute that SQL Query in SSMS all of the related data is being retrieved as expected, so the issue does not appear to be in the query.当我在 SSMS 中执行 SQL 查询时,所有相关数据都按预期检索,因此问题似乎不在查询中。 It is how that data is then being populated into the underlying objects that is the issue.问题在于数据是如何填充到底层对象中的。

Long story short, you're setting up this empty data you're seeing, and EFC won't overwrite it if you do.长话短说,您正在设置您看到的这个空数据,如果您这样做,EFC 不会覆盖它。 Comment out/delete all your entity constructors that are doing things like this:注释掉/删除所有执行以下操作的实体构造函数:

    public Client()
    {
        Person = new Person(0, "", "");
        ContactType = new ContactType();
        ReferralPerson = new ReferralPerson();
        NewsletterOption = new NewsletterOption();
    }

If the entities are made so as to look like those presented in the question , everything works如果制作的实体看起来像问题中出现的实体,则一切正常

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 Entity Framework Core 在导航属性上调用表达式 - Entity Framework Core Invoke an Expression on Navigation property Entity Framework Core:基于导航属性的集合 - Entity Framework Core: navigation property based collection Entity Framework Core:填充关系导航属性 - Entity Framework Core : populating relationship navigation property 如何更新 Entity Framework Core 中的单个属性 - How to update a single property in Entity Framework Core 实体框架导航属性 - Entity Framework navigation property 如何使用 Entity Framework Core 中的导航属性获取内部连接 - How to get Inner Join using navigation property in Entity Framework Core 两个上下文之间的实体框架核心导航属性 - Entity Framework core navigation property between two contexts 使用 Entity Framework Core 在抽象基类中映射导航属性 - Mapping navigation property in abstract base class with Entity Framework Core Entity Framework Core 多对多更改导航属性名称 - Entity Framework Core Many to Many change navigation property names 在实体框架核心的多对多关系中获取导航属性时出错 - Error in getting navigation property in a many to many relationship in entity framework core
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM