C# InvalidOperationException:无法使用表';XX1和#x27;对于实体类型';xxxx2&x27;因为它用于实体类型';XX1和#x27;
我试图先在实体框架代码中创建一个数据库,但我总是遇到这样的错误:C# InvalidOperationException:无法使用表';XX1和#x27;对于实体类型';xxxx2&x27;因为它用于实体类型';XX1和#x27;,c#,asp.net-mvc,visual-studio,entity-framework,ef-code-first,C#,Asp.net Mvc,Visual Studio,Entity Framework,Ef Code First,我试图先在实体框架代码中创建一个数据库,但我总是遇到这样的错误: InvalidOperationException:无法对实体类型使用表“设备” “IpMac”,因为它正用于实体类型“Device”,并且主键{'DeviceIP'}和主键{'DeviceID'}之间没有关系。” 这些是我的模型类: public class IpMac { [Key] public string DeviceIP { get; set; } //[ForeignKey("Device")
InvalidOperationException:无法对实体类型使用表“设备” “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; }
}
公共类IpMac
{
[关键]
公共字符串DeviceIP{get;set;}
//[外键(“设备”)]
公共int设备ID{get;set;}
公共字符串DeviceMAC{get;set;}
//公用设备设备{get;set;}
公用ICollection设备{get;set;}
}
公共类设备
{
//[关键]
公共int设备ID{get;set;}
公共字符串DeviceName{get;set;}
公共字符串用户名{get;set;}
//公共字符串DeviceMAC{get;set;}
公共IpMac IpMac{get;set;}
}
下面是我的“DbContext”类:
公共类DeviceContext:DbContext
{
公用设备上下文(DbContextOptions选项):基本(选项)
{
}
公共数据库集设备{get;set;}
公共DbSet IpMacs{get;set;}
模型创建时受保护的覆盖无效(ModelBuilder ModelBuilder)
{
modelBuilder.Entity().ToTable(“设备”);
modelBuilder.Entity().ToTable(“设备”);
Log(“DeviceContext:数据库和表集”);
}
}
您的设备上下文不应该为表使用不同的表名吗
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.");
}
}
公共类DeviceContext:DbContext
{
公用设备上下文(DbContextOptions选项):基本(选项)
{
}
公共数据库集设备{get;set;}
公共DbSet IpMacs{get;set;}
模型创建时受保护的覆盖无效(ModelBuilder ModelBuilder)
{
modelBuilder.Entity().ToTable(“IpMac”);
modelBuilder.Entity().ToTable(“设备”);
Log(“DeviceContext:数据库和表集”);
}
}
噢,哇,我已经找了半天的答案了,非常感谢你。是啊,有时候我们会被眼前的简单事情弄瞎眼睛:)不要感到孤独!
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.");
}
}