I use Entity Framework Core. I have entity with action delegate property:
public class Student
{
public int Id { get; set; }
public string Name { get; set; }
public Action<string, int, decimal, int> RateAction { get; set; }
}
var student1 = new Student();
student1.Id = 1;
student1.Name = "Test 1";
student1.RateAction = (s, a, b, c) =>
{
var m = a * c b;
s = $"{s} - {m}";
};
var student2 = new Student();
student1.Id = 2;
student1.Name = "Test 2";
student1.RateAction = (s, a, b, c) =>
{
b = c * b / a;
};
Student entity is part Entity Framework context:
public class MyContext : DbContext
{
...
public DbSet<Student> Students { get; set; }
...
}
I have fluent API configuration for the entity:
public class StudentConfiguration : IEntityTypeConfiguration<Student>
{
public void Configure(EntityTypeBuilder<Student> builder)
{
builder.ToTable("Student");
builder.HasKey(x => x.Id);
builder.Property(x => x.Name).IsRequired();
// Add config for RateAction property
}
}
How store RateAction property in database and configure with entity framework?
CodePudding user response:
I think you need a Table for the property RateAction and in the Table Student you need a FK for RateAction.
CodePudding user response:
I would recommend not storing the action. Databases are for data and code is for configuring functionality/actions. Instead, store instances of inherited Student classes, that implement the desired action/logic and return a calculated value, which can be further formatted as needed:
public abstract class Student
{
public int Id { get; set; }
public string Name { get; set; }
public abstract decimal RateAction(int a, decimal b, int c);
}
public class MultiplyingStudent : Student
{
public override decimal RateAction(int a, decimal b, int c) => a * c b;
}
public class DividingStudent : Student
{
public override decimal RateAction(int a, decimal b, int c) => c * b / a;
}
These child classes, and any others, will store just fine inside your DbSet of Student objects:
var m = new MultiplyingStudent();
var d = new DividingStudent();
...
var context = new MyContext();
context.Students.Add(m);
context.Students.Add(d);
EF will add a discriminator column as a way to help it turn rows back into instances once you do a select statement:
var x = context.Students.Select(s => s.Id == <int>);
var result = x.RateAction(<int>, <decimal>, <int>);
