+-
C#-InvalidOperationException:无法将表“ xxxx1”用于实体类型“ xxxx2”,因为它已用于实体类型“ xxxx1”
我试图首先以实体框架代码创建数据库,但是我总是收到这样的错误:

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’}.”

这些是我的模型类:

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; }
}

这是我的“ 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.");
    }
}
最佳答案
您的设备上下文是否应该为表使用不同的表名?

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.");
    }
}
点击查看更多相关文章

转载注明原文:C#-InvalidOperationException:无法将表“ xxxx1”用于实体类型“ xxxx2”,因为它已用于实体类型“ xxxx1” - 乐贴网