为了账号安全,请及时绑定邮箱和手机立即绑定

一对多流利的实体框架

一对多流利的实体框架

C#
红糖糍粑 2021-05-04 09:10:59
每隔半小时,将收到来自移动设备的请求。可以在设备表中验证移动设备,然后将记录添加到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);    }
查看完整描述

1 回答

?
月关宝盒

TA贡献1772条经验 获得超5个赞

您可以尝试在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类中为Ping添加导航属性,如下所示


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



查看完整回答
反对 回复 2021-05-08
  • 1 回答
  • 0 关注
  • 141 浏览

添加回答

举报

0/150
提交
取消
意见反馈 帮助中心 APP下载
官方微信