简体   繁体   中英

Doesn't retrieve the related table data in Entity Framework Core with PostgreSQL

I'm trying Entity Framework Core with PostgreSQL. I have two tables that are one to many relationship. According to the relationship, Movie has a Year and Year has many Movies. But Once I retrieve movies, the year doesn't contain in it, year in each movie is null unless retrieving the years. But after retrieving the years, movies becoming having the years. When I move the year retrieving code line to up. It's happened the same. The years don't have the movies unless retrieving the movies. Then, After retrieving the movies, the selected years becoming having the movies. Can anyone know how to solve it? It's like lazy loading.

Here is my two entity.

public class T_MOVIE
{
    [Key]
    public long Oid { get; set; }
    public string Name { get; set; }
    public string Description { get; set; }
    public DateTime CreatedDate { get; set; }
    public long? YearOid { get; set; }
    [ForeignKey("YearOid")]
    public T_YEAR MOVIE_YEAR { get; set; }
}

public class T_YEAR
{
    public T_YEAR()
    {
        this.YEAR_MOVIEs = new HashSet<DataModel.T_MOVIE>();
    }
    [Key]
    public long Oid { get; set; }
    public string Name { get; set; }
    public ICollection<T_MOVIE> YEAR_MOVIEs { get; set; }
}

And in the OnModelCreating,

protected override void OnModelCreating(ModelBuilder builder)
{
    builder.Entity<T_MOVIE>().HasKey(m => m.Oid);
    builder.Entity<T_MOVIE>().HasOne(m => m.MOVIE_YEAR).WithMany(m => m.YEAR_MOVIEs);

    builder.Entity<T_YEAR>().HasKey(m => m.Oid);
    builder.Entity<T_YEAR>().HasMany(m => m.YEAR_MOVIEs).WithOne(m => m.MOVIE_YEAR);
}

Then, I retrieve the data.

var movies = _db.T_MOVIE.ToList();
var years = _db.T_YEAR.ToList();

Thank you.

You have to add "Include()" in your query. Unless doing that, it returns null relations.

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