简体   繁体   中英

One to Many Fluent Entity Framework

After every half an hour, will get a request from Mobile device. Validating Mobile is available in Device Table then adding record into Ping Table. Same Tables are mapped on DB using Entity Franmework.

Could any one advise me how to map Device.Id (Primary Key) into Ping.IdDevice (Foreign Key), releationship will be one-to-many using 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);
    }

you can try to add a navigation property for Device in Ping class as shown below:

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

Then in the Device class add navigation property for Pings as shown below

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
}

Finally in OnModelCreating add the below mapping:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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