Как получить таблицу, используя отношения в Entity Framework - PullRequest
0 голосов
/ 04 июня 2019

Я использую EF Core 2.1 и пытаюсь получить профиль из аутентификации, но каждый раз, когда я его получаю, я обнаруживаю, что он нулевой, и я не знаю, в чем проблема. А для аутентификации я могу получить профили.

Объекты:

[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);
}

Как правильно использовать отношения

1 Ответ

1 голос
/ 04 июня 2019

Вам необходимо использовать , включая для дочернего объекта и изменить Find на SingleOrDefault.

Добавить Включить

var user = _context.Authentications.Include(p => p.Profile).SingleOrDefault(currentUserId);
return user.Profile;
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...