猿问

一对多流利的实体框架

每隔半小时,将收到来自移动设备的请求。可以在设备表中验证移动设备,然后将记录添加到Ping表中。使用实体Franmework将相同的表映射到DB。


谁能告诉我如何将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);

    }


红糖糍粑
浏览 142回答 1
1回答

月关宝盒

您可以尝试在Ping类中为Device添加导航属性,如下所示:public class Ping{&nbsp; &nbsp; public long Id { get; set; }&nbsp; &nbsp; public long IdDevice { get; set; }&nbsp; &nbsp; public virtual Device Device { get; set; }//Newly added&nbsp; &nbsp; public string Request { get; set; }&nbsp; &nbsp; public string Response { get; set; }&nbsp; &nbsp; public int RspCode { get; set; }&nbsp; &nbsp; public DateTime CreatedDateTime { get; set; }}然后在Device类中为Ping添加导航属性,如下所示public class Device{&nbsp; &nbsp; public long Id { get; set; }&nbsp; &nbsp; public string Uid { get; set; }&nbsp; &nbsp; public Type Type { get; set; }&nbsp; &nbsp; public Status Status { get; set; }&nbsp; &nbsp; 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);
随时随地看视频慕课网APP
我要回答