0

I am new to Entity Framework and I am working with a db first model and I am attempting to store some data. I have a table (table1) that is related to another table (table2), so EF created a navigation property between the two. Do I set the navigation property within table1 or do I add a new entity to insert table2 with the record id of table1? Table2 has a foreign key to Table1's id field. I need table2 to populate that. Also from my understanding the id field will be set by EF as an incremental int value?

public partial class Table1
{
    public int Id1 {get; set;}
    public virtual ICollection<Table2> Table2s {get; set;}
}


public partial class Table2
{
    public int Id2 {get; set;}
    public int somedata {get; set;}
    public int Id1 {get; set;}
    public virtual Table1 Table1 {get; set;}
}


using(TablesEntities context = new TablesEntities())
{
    var data = new Table1 
    {
        Table2s = new [] { new Table2s
        {
            somedata = 123,
            id1 = ???
        }}
    }
}
Kevlwig
  • 133
  • 2
  • 11
  • Yes, and both will work. – Stefan Jul 07 '19 at 19:02
  • @Stefan So youre same once I add the table one entity EF will generate an Id for table1 and then table2 will inherently get table1 id? – Kevlwig Jul 07 '19 at 19:12
  • 1
    Yes, make sure you add them through the collection... so, you dont need to set the id's. Although, your case is tricky because there is an m : n relation involved... nevertheless, it should work. – Stefan Jul 07 '19 at 19:17
  • @Stefan How would I add the id's through the collection? – Kevlwig Jul 07 '19 at 19:20
  • As correctly stated by Stefan, you've got a many-to-many association. These associations can only be set as [independent associations](https://stackoverflow.com/questions/12606948/what-are-independent-associations-and-foreign-key-associations). That is, you can't set an Id property and `Table2.Id1` can't be a FK to `Table1`. – Gert Arnold Jul 07 '19 at 20:26
  • @GertArnold its only a one (0.. 1) to many (*) relation – Kevlwig Jul 07 '19 at 22:05
  • Now it is :). Just always add to the collection. Replacing it may have adverse side effects, like deleting existing items when they're loaded. – Gert Arnold Jul 08 '19 at 21:04

0 Answers0