【问题标题】:InvalidOperationException: Cannot use table 'xxxx1' for entity type 'xxxx2' since it is being used for entity type 'xxxx1'InvalidOperationException:不能将表“xxxx1”用于实体类型“xxxx2”,因为它正在用于实体类型“xxxx1”
【发布时间】:2018-03-09 23:28:21
【问题描述】:

我正在尝试先在实体框架代码中创建一个数据库,但我总是收到这样的错误:

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

这是我的“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.");
    }
}

【问题讨论】:

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


    【解决方案1】:

    您的设备上下文是否应该为表使用不同的表名?

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

    【讨论】:

    • 哇哇找了半天,非常感谢
    • 是的,有时我们会被眼前的简单事物蒙蔽:)不要感到孤独!
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多