0

I have a simple C# class that is a model of a table I'd like to have in SQL Server. Here's the class:

public class Device
{
    public int Id { get; set; }
    public DeviceType DeviceType { get; set; }
    public IList<Device> ConnectedDevices { get; set; }
}

When I create a migration, here's what Entity Framework generates for this table:

    CreateTable(
        "dbo.Devices",
        c => new
            {
                Id = c.Int(nullable: false, identity: true),
                Device_Id = c.Int(),
                DeviceType_Id = c.Int(),
            })
        .PrimaryKey(t => t.Id)
        .ForeignKey("dbo.Devices", t => t.Device_Id)
        .ForeignKey("dbo.DeviceTypes", t => t.DeviceType_Id)
        .Index(t => t.Device_Id)
        .Index(t => t.DeviceType_Id);

I see that it creates Id and Device_Type_Id - these two are fine. But why does it want to create Device_Id, which is Int? I don't need that - I want to have a one-to-many relationship (one device can be a master of many devices). So why doesn't it reflect my ConnectedDevices property properly?

//EDIT: When I think about it more, actually I should get many-to-many relation. Every device can have many devices that it controls. So EF should generate for me additional table to satisfy that. I can't understand why it doesn't do that

mnj
  • 2,539
  • 3
  • 29
  • 58
  • I saw this link, but I thought that newer versions of EF can handle it better - it's obvious that I want to create many-to-many. Why does EF transform it into one-to-many? – mnj Oct 07 '17 at 17:27
  • Why do you think it's *obvious* that you want many-to-many? Based on what rule? Self referencing one-to-many is also commonly used for storing tree like data. – Ivan Stoev Oct 07 '17 at 17:28
  • @IvanStoev Can you give an example? I'm interested to learn something. I think that if I have a IList property inside Device class it is obvious that I want to have many devices to be bound to other device. Since any device is of Device type it becomes many-to-many. – mnj Oct 07 '17 at 18:43
  • 1
    For instance `public class Folder { public int Id { get; set; } public ICollection SubFolders { get; set; } }` and many similar. This is one-to-many in case it's not "obvious" :) – Ivan Stoev Oct 07 '17 at 19:18

1 Answers1

0

Lets say you have a child device and you want to learn parent of the device. EF uses that id to access parent device.

Edit: What you configured is not many to many. Ef can not track parent devices. you should define devices like this.

    public class Device
    {
      public int Id { get; set; }
      public DeviceType DeviceType { get; set; }
      public IList<Device> InConnectedDevices { get; set; }
      public IList<Device> OutConnectedDevices { get; set; }
    }

Then configure it in Fluent API. If you are using EF Core. You need another solution.

Okan Aslankan
  • 3,016
  • 2
  • 21
  • 26