InvalidOperationException: 由于该表正在被实体类型“xxxx1”使用,因此无法将其用于实体类型“xxxx2”。

20
我正在尝试使用实体框架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; }
}

这是我的 "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.");
    }
}
1个回答

29

你的设备上下文是否应该对表格使用不同的表名?

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.");
    }
}

1
哦,哇,我已经找了半天的答案了,非常感谢你。 - timo stevens
2
是的,有时候我们会被那些明摆着的简单事物所迷惑 :) 不要感到孤独! - Kell

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接