繁体   English   中英

带有元数据的实体框架一对多联接表

[英]Entity Framework one-to-many join table with metadata

我正在尝试在Entity Framework中实现联接表的某些内容,但似乎无法真正获得任何结果。

我有两个主要对象:

public class Device
{
    [Key]
    public int Id { get; set; }

    public virtual ICollection<Connection> Slaves { get; set; }
}

public class Connection
{
    [Key]
    public int Id { get; set; }

    public virtual Device Master { get; set; }
    public virtual Device Slave  { get; set; }

    public DateTime       Start  { get; set; }
    public DateTime       End    { get; set; }
}

public class Context : DbContext
{
    public virtual DbSet<Device> Devices { get; set; }

    protected override void OnModelCreating(DbModelBuilder modelBuilder)
    {
         // Fluent API???
    }
}

换句话说:我有一个Device类,可以包含多个从设备。 从设备使用联接表进行耦合,并且它们的关联仅在“ End时间戳”小于当前时间时才有效。

我一直在尝试使其与Fluent API一起使用,但无济于事。 为了不模糊我的问题,我暂时不做任何尝试。 我能够使用正确的FK列创建联接表,但是在查询从属列表时,它返回null 调查生成的SQL,甚至没有查询联接表,因此有点道理=)

您能帮我解决这种(很少见的)联系吗? 另外,如果我要解决所有这些错误,请告诉我; 尚无定论。

谢谢!

更新

好的,这样我就可以进行一对多的关联了。 我遵循@DavidG的建议,并将“从属列表”移至Device类,并将其变为虚拟。 这似乎是关键的一步,因为添加virtual突然使EF查询连接表。

我将此添加到我的上下文中:

public class Context : DbContext
{
    public virtual DbSet<Device>     Devices     { get; set; }
    public virtual DbSet<Connection> Connections { get; set; }

    protected override void OnModelCreating(DbModelBuilder modelBuilder)
    {
          // Create a one-to-many for the connections
        modelBuilder.Entity<Device>().HasMany(g => g.Devices).WithRequired(c => c.Master);
        modelBuilder.Entity<Connection>().HasRequired(c => c.Slave).WithMany().WillCascadeOnDelete(false);

        modelBuilder.Entity<Connection>()
            .Property(f => f.Start)
            .HasColumnType("datetime2")
            .HasPrecision(0);

        modelBuilder.Entity<Connection>()
            .Property(f => f.End)
            .HasColumnType("datetime2")
            .HasPrecision(0);
    }
}

现在,我至少要恢复所有的从属设备( new Context().Devices )。 谢谢! 我仍然不知道的是如何过滤连接属性,例如: End == null

任何帮助,将不胜感激!

试试看,

public class Device
{
      [Key]
    public int Id { get; set; }

    public ICollection<Connection> Slaves { get; set; }
}

public class Connection
{
    [Key]
    public int Id { get; set; }

    [ForeignKey("Master")]
    public int MasterDeviceId { get; set; }
    [ForeignKey("Slave")]
    public int SlaveDeviceId { get; set; }

    public virtual Device Master { get; set; }
    public virtual Device Slave  { get; set; }

    public DateTime       Start  { get; set; }
    public DateTime       End    { get; set; }
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM