Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

InvalidOperationException: Cannot use table 'xxxx1' for entity type 'xxxx2' since it is being used for entity type 'xxxx1'

i'm trying to make a database in entity-framework code-first but im always getting a error like this:

InvalidOperationException: Cannot use table 'Device' for entity type 'IpMac' since it is being used for entity type 'Device' and there is no relationship between the primary key {'DeviceIP'} and the primary key {'DeviceID'}."

these are my model classes:

public class IpMac
{
    [Key]
    public string DeviceIP { get; set; }
    //[ForeignKey("Device")]
    public int DeviceID { get; set; }
    public string DeviceMAC { get; set; }

    //public Device Device { get; set; }
    public ICollection<Device> Device { get; set; }
}
public class Device
{
    //[Key]
    public int DeviceID { get; set; }
    public string DeviceName { get; set; }
    public string UserName { get; set; }
    //public string DeviceMAC { get; set; }

    public IpMac IpMac { get; set; }
}

and here is my "DbContext" class:

public class DeviceContext : DbContext
{
    public DeviceContext(DbContextOptions<DeviceContext> options) : base (options)
    {
    }

    public DbSet<Device> Devices { get; set; }
    public DbSet<IpMac> IpMacs { get; set; }

    protected override void OnModelCreating(ModelBuilder modelBuilder)
    {

        modelBuilder.Entity<IpMac>().ToTable("Device");
        modelBuilder.Entity<Device>().ToTable("Device");
        Logger.Log("DeviceContext: Database & Tables SET.");
    }
}
like image 739
timo stevens Avatar asked Sep 28 '17 09:09

timo stevens


1 Answers

Shouldnt your device context use different table names for the tables?

public class DeviceContext : DbContext
{
    public DeviceContext(DbContextOptions<DeviceContext> options) : base (options)
    {
    }

    public DbSet<Device> Devices { get; set; }
    public DbSet<IpMac> IpMacs { get; set; }

    protected override void OnModelCreating(ModelBuilder modelBuilder)
    {
      modelBuilder.Entity<IpMac>().ToTable("IpMac");
      modelBuilder.Entity<Device>().ToTable("Device");
      Logger.Log("DeviceContext: Database & Tables SET.");
    }
}
like image 180
Kell Avatar answered Nov 04 '22 15:11

Kell