简体   繁体   中英

InverseProperty Entity Framework 7

I am facing a problem with EF7 inverse property. There are two entities that are connected like this.

public class Employee
    {
        public int Id { get; set; }
    }

public class Review
{
    public int Id { get; set; }

    [Required]
    public virtual Employee Employee { get; set; }

    [Required]
    public Employee Manager { get; set; }
 }

I want to access a list of the reviews when I start to query my employees, so I tried to do this:

public class Employee
    {
        public Employee()
        {
            Reviews = new List<Review>();
        }
        public int Id { get; set; }

        [InverseProperty("Employee")]
        public virtual ICollection<Review> Reviews { get; set; }
    }

With this, the query is not well made and return this error:

Invalid column name 'EmployeeId1' .

This is the part of the query where is the error:

SELECT [ua].[Id], [r].[EmployeeId], [r].[EmployeeId1], [r1].[EmployeeId], [r1].[EmployeeId1]
FROM [UserAssessment] AS [ua]
LEFT JOIN [Review] AS [r] ON [ua].[ReviewId] = [r].[Id]
LEFT JOIN [Review] AS [r1] ON [ua].[ReviewId] = [r1].[Id]

Anyone know what can I do?

UPDATE

This statement is generating the query:

return this.DbSet
.Include(ua => ua.Employee).ThenInclude(t => t.Role)
.Include(ua => ua.Review).ThenInclude(rt => rt.ReviewType)
.Include(ua => ua.Review).ThenInclude(rt => rt.Manager).ThenInclude(r => r.Role)

I have to access with those same includes because lazy loading is not available on EF7 yet.

You need the InverseProperty on both the Employee and Review

public class Review
{
    public int Id { get; set; }

    [Required]
    [InverseProperty("Reviews")]
    public Employee Employee { get; set; }

    [Required]
    public Employee Manager { get; set; }
 }

public class Employee
    {
        public int Id { get; set; }

        [InverseProperty("Employee")]
        public ICollection<Review> Reviews { get; set; }
    }

Should work. I have a similar setup where it creates the navigation without creating any new fields. If this doesn't work let me know and I'll spin up a test project.

Also note, that EF7 currently ignores virtual and this does not have meaning like it did in EF6.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM