I have some custom classes, such as BarcodeDevice
and LightDevice
, which are derived from a base class called Device
. I have the following requirements:
Device
table.Dll
file. Therefore, once the project goes live, the code cannot be changed.Device
object from the database using DbContext
. I am currently using Discriminator
and it works, but it only runs once, and thus does not support adding custom classes at runtime. How can I solve this issue?
DbContext
:
public class ApplicationDbContext : IdentityDbContext
{
public ApplicationDbContext(DbContextOptions<ApplicationDbContext> options)
: base(options)
{
}
public DbSet<Device> Devices { get; set; }
protected override void OnModelCreating(ModelBuilder modelBuilder)
{
base.OnModelCreating(modelBuilder);
// Configure device type for each type.
modelBuilder.Entity<BarcodeDevice>()
.HasDiscriminator(p => p.Type)
.HasValue(nameof(BarcodeDevice));
modelBuilder.Entity<LightDevice>()
.HasDiscriminator(p => p.Type)
.HasValue(nameof(LightDevice));
}
}
Custom Class:
public class BarcodeDevice : Device
{
[Required]
public string Type { get; set; }
private SerialPort serial { get; set; }
private string barcodeValue { get; set;}
// other properties
}
Service:
public class DeviceService : IDeviceService
{
// Some variables
public DeviceService(IServiceScopeFactory serviceScopeFactory)
{
_serviceScopeFactory = serviceScopeFactory;
var dbContext = _serviceScopeFactory.CreateScope()
.ServiceProvider.GetRequiredService<ApplicationDbContext>();
Devices = dbContext.Devices.ToList();
for (int i = 0; i < Devices.Count; i++)
{
Devices[i].StartInstance();
Devices[i].OnMessageSend += Device_OnMessageSend;
}
_mqttClient = _serviceScopeFactory.CreateScope()
.ServiceProvider.GetRequiredService<IResolverMqttClient>();
_mqttClient.OnMqttMessageReceived += MqttClient_OnMqttMessageReceived;
}
// some methods
}
Your options.
Push back on 3). Do you really need that?
don't use EF,
or
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.