【问题标题】:One to Many Fluent Entity Framework一对多流畅的实体框架
【发布时间】:2018-04-23 09:01:32
【问题描述】:

每半小时后,将收到来自移动设备的请求。验证手机在设备表中可用,然后将记录添加到 Ping 表中。使用实体框架将相同的表映射到数据库。

谁能告诉我如何将 Device.Id(主键)映射到 Ping.IdDevice(外键),使用 Fluent Api 的关系将是一对多的。

public class Ping 
{
    public long Id { get; set; }
    public long IdDevice { get; set; }
    public string Request { get; set; }
    public string Response { get; set; }
    public int RspCode { get; set; }
    public DateTime CreatedDateTime { get; set; }
}

    public class Device {
    public long Id { get; set; }
    public string Uid { get; set; }
    public Type Type { get; set; }
    public Status Status { get; set; }
}

        protected override void OnModelCreating(DbModelBuilder modelBuilder) {

        modelBuilder.Entity<Device>().HasKey(d => d.Id);
        modelBuilder.Entity<Device>().Property(d => d.Id).HasDatabaseGeneratedOption(DatabaseGeneratedOption.Identity);


        modelBuilder.Entity<Device>().Property(d => d.Uid).HasMaxLength(8);
        modelBuilder.Entity<Device>().HasRequired(d => d.Uid);

        modelBuilder.Entity<Ping>().HasKey(p => p.Id);
        modelBuilder.Entity<Ping>().Property(p => p.Id).HasDatabaseGeneratedOption(DatabaseGeneratedOption.Identity);



        base.OnModelCreating(modelBuilder);
    }

【问题讨论】:

    标签: c# database entity-framework


    【解决方案1】:

    您可以尝试在 Ping 类中为 Device 添加一个导航属性,如下所示:

    public class Ping
    {
        public long Id { get; set; }
        public long IdDevice { get; set; }
        public virtual Device Device { get; set; }//Newly added
        public string Request { get; set; }
        public string Response { get; set; }
        public int RspCode { get; set; }
        public DateTime CreatedDateTime { get; set; }
    }
    

    然后在 Device 类中为 Pings 添加导航属性,如下所示

    public class Device
    {
        public long Id { get; set; }
        public string Uid { get; set; }
        public Type Type { get; set; }
        public Status Status { get; set; }
        public virtual List<Ping> Pings { get; set; } //Newly added
    }
    

    最后在 OnModelCreating 中添加如下映射:

    modelBuilder.Entity<Device>().HasMany(d => d.Pings).WithRequired(p => p.Device).HasForeignKey(p => p.IdDevice);
    

    【讨论】:

    • 在 Ping 类中添加以下行就足够了 public virtual Device Device { get;放; }
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2019-07-05
    • 1970-01-01
    • 1970-01-01
    • 2015-05-22
    • 1970-01-01
    • 1970-01-01
    • 2015-10-13
    相关资源
    最近更新 更多