Using PropertyBuilder.HasValueGenerator and Connecting to Database Context

asp.net-core entity-framework-core

Question

I would like to be able to look up information in my database and generate a default value for one of my entity's fields based on the results.

Problem is, I don't know how to inject the EF context into the creation of the ValueGenerator. The way I am doing it now requires a parameterless constructor.

Here's what I have so far.

In my DbContext OnModelCreating:

            entity.Property(e => e.SampleNumber)
                .HasColumnName("SampleNumber")
                .HasMaxLength(25)
                .HasValueGenerator<SampleIDGenerator>();

My ValueGenerator:

public class SampleIDGenerator : Microsoft.EntityFrameworkCore.ValueGeneration.ValueGenerator
{
    public override bool GeneratesTemporaryValues => false;

    private readonly WellWaterEntities db;

    public SampleIDGenerator(WellWaterEntities context)
    {
        db = context;
    }

    protected override object NextValue(EntityEntry entry)
    {
        string lastitem = db.Samples.OrderByDescending(x => x.SampleNumber)
            .FirstOrDefault().SampleNumber;

        if (lastitem != null)
        {
            int lastSequence;
            if (int.TryParse(lastitem.Substring(5, 4), out lastSequence))
            {
                return lastitem.Substring(0, 5) + (lastSequence + 1).ToString("0000");
            }
        }
        return DateTime.Now.Year.ToString() + "-" + "0001";
    }
}
1
2
3/20/2019 9:40:12 PM

Popular Answer

The NextValue() parameter EntityEntry entry is populated with DbContext entry.Context.

    protected override object NextValue(EntityEntry entry)
    {
        WellWaterEntities db = (WellWaterEntities) entry.Context;

        ...
    }
0
3/21/2019 12:43:50 AM


Related Questions





Related

Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow
Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow