c# - 无效操作异常 : Cannot use table 'xxxx1' for entity type 'xxxx2' since it is being used for entity type 'xxxx1'

标签 c# asp.net-mvc visual-studio entity-framework ef-code-first

我试图在代码优先的 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/

相关文章:

c# - MVC - Controller 到服务层通信

javascript - jQuery 在按钮单击时获取最接近的表单

c# - 如何在没有 Visual Studio 帮助的情况下使用 Microsoft.VisualStudio.TestTools.UnitTesting 为程序添加单元测试?

.net - VS解决方案,项目与DLL最佳实践

visual-studio - TFS 2013 不会将构建输出复制到放置文件夹

c# - 定向鼠标事件 [DllImport ("user32.dll")] 单击,双击

c# - 如何在加载所有相关数据之前不显示 JQuery 对话框?

c# - 检查显示是否被 Windows 电源管理关闭

c# - WPF 窗口 ShowDialog() 导致无法设置可见性或调用 Show

jquery - 阻止自定义验证器在每次击键时触发