简体   繁体   English

如何使用实体框架中的关系获取表

[英]How to get table using relationships in Entity Framework

I am using EF Core 2.1 and i'm trying to get Profile from Authentication but every time i get it i found it null and i don't now where is the problem. 我正在使用EF Core 2.1,并且我尝试从身份验证获取配置文件,但是每次获取它时,我都发现它为null,现在不是问题所在了。 And for authentication i can get profiles. 对于身份验证,我可以获取配置文件。

Entities: 实体:

[Table("USER_AUTHENTICATION")]
public class Authentication
{
    public int ID { get; set; }
    //...some code
    [ForeignKey("ProfileID")]
    public Profile Profile { get; set; }
    public virtual int ProfileID { get; set; }

}

[Table("USER_PROFILE")]
public class Profile
{
    public Profile()
    {
        Authentication = new HashSet<Authentication>();
    }

    public int ID { get; set; }
    //... some code
    public virtual ICollection<Authentication> Authentication { get; set; }

}

DataContext 数据上下文

public DataContext(DbContextOptions<DataContext> options) : base(options) { }

public DbSet<Authentication> Authentications { get; set; }
public DbSet<Profile> Profiles { get; set; }

public Profile GetById(int currentUserId)
{
     var user = _context.Authentications.Find(currentUserId);
     Console.WriteLine(user.Profile); //<--- here is the probelm null//
     return _context.Profiles.Find(user.ProfileID);
}

How can i use relations with correct way 我如何以正确的方式使用关系

You need use include for sub-entity and change Find to SingleOrDefault . 您需要将include用于子实体,并将Find更改为SingleOrDefault

Add Include 添加包含

var user = _context.Authentications.Include(p => p.Profile).SingleOrDefault(currentUserId);
return user.Profile;

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

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