我试图在代码优先的 Entity Framework 中创建一个数据库,但我总是收到这样的错误:
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# - 无效操作异常 : Cannot use table 'xxxx1' for entity type 'xxxx2' since it is being used for entity type 'xxxx1' ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46465430/