InvalidOperationException:无法将表“ xxxx1”用于实体类型“ xxxx2”,因为它已用于实体类型“ xxxx1”

tim*_*ens 5 c# asp.net-mvc entity-framework visual-studio ef-code-first

我试图首先以实体框架代码创建数据库,但是我总是收到这样的错误:

InvalidOperationException:无法将表'Device'用于实体类型'IpMac',因为它已用于实体类型'Device',并且主键{'DeviceIP'}与主键{'DeviceID'}之间没有关系。”

这些是我的模型类:

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; }
}
Run Code Online (Sandbox Code Playgroud)

这是我的“ DbContext”类:

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.");
    }
}
Run Code Online (Sandbox Code Playgroud)

Kel*_*ell 6

您的设备上下文是否应该为表使用不同的表名?

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.");
    }
}
Run Code Online (Sandbox Code Playgroud)

  • 是的,有时我们会被眼前的简单事物所蒙蔽:)不要感到孤独! (2认同)