简体   繁体   中英

C# EntityFramework .NETCore 2.0 Many-to-Many

.. Hello I know there's been already plenty of questions on this, but still can't get it right no matter what. I need a many-to-many with custom join table, but every time I try to fetch collection it's still empty.

First class:

public class Test1 {

    [Key]
    public int id { get; set; }

    public virtual ICollection<TestToTest> others { get; set; }

    public Test1() {
        others = new HashSet<TestToTest>();
    }
}

Second one:

public class Test2 {

    [Key]
    public int id { get; set; }

    public virtual ICollection<TestToTest> others { get; set; }

    public Test2() {
        others = new HashSet<TestToTest>();
    }

}

And the join table:

public class TestToTest {

    [Key]
    public int id { get; set; }

    [ForeignKey("Test1")]
    public int test1Id { get; set; }

    [ForeignKey("Test2")]
    public int test2Id { get; set; }

    public virtual Test1 test1 { get; set; }
    public virtual Test2 test2 { get; set; }

}

But still when I try to get one of them with query like:

var cont = new MyContext(); //DbContext
Test1 t1 = cont.test1.Find(1); // Fetches first class ok
var tt = t1.others; // Empty array

I really have no idea what more I'm missing there in other to make it work. If I add a new one to context then it's ok... as long as it's cached -> and it does write row into db. But after restart (without any cache in context), field 'others' is always empty.

Thanks for any help in advance.

It's not loading as child relationship are setup for Eager Loading . Eager loading is the process whereby a query for one type of entity also loads related entities as part of the query, so that we don't need to execute a separate query for related entities. Eager loading is achieved using the Include() method. So if the relationship entity is not loaded using include then it would NOT be loaded.

Change the code as

Test1 t1 = cont.test1.Include(t => t.others).SingleOrDefault(t => t.id == 1); 

You can read about Eager Loading at this Microsoft document.

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