Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
186 views
in Technique[技术] by (71.8m points)

c# - Entity Framework Core: Check if an entity part of a One-to-Many relationship exists on Add

I am very new to Entity Framework Core (Entity Framework in General), and I have watched several tutorial videos and done a Pluralsight course.

I am using ASP.NET Web API, and I want to add a new entity, that has a One-to-Many relationship. The models are as follows:


"Parent" Class:

public partial class VerificationVoltage
{
    public int Id { get; set; }

    public DateTime Date { get; set; }

    public string Type { get; set; }

    public int VerificationVoltageSerialId { get; set; }

    public VerificationVoltageSerial Serial { get; set; }
}

"Child" Class:

public class VerificationVoltageSerial
{
    [DatabaseGenerated(DatabaseGeneratedOption.Identity)]
    public int Id { get; set; }
        
    [Required]
    [MaxLength(20)]
    public string Serial { get; set; }

    public List<VerificationVoltage> VerificationVoltage { get; set; }
}

I would like the VerificationVoltageSerial.Serial to be unique, and that the database will first check whether or not the serial exists, before adding the newly added serial (The serials themselves are unique).

Is there a way to do the following: If a row with the same serial exist, as what needs to be added, entity framework then automatically selects the Serial and SerialId and populates the Entity that is being added, with the serial selected from the database.

This is what I am doing currently, I feel that this is a very manual check, an maybe there is something more automatic: (i.e I want it to wrok, even if I remove the IF Statement and the exisitngEntry query in the controller)

[HttpPost]
public async Task<VerificationVoltage> AddVerificationVoltage(VerificationVoltage verificationVoltage)
{
    var exisitngEntry = await repository.GetBySerialNoTracking(verificationVoltage.Serial.Serial)
                                        .ConfigureAwait(false);
    if (exisitngEntry != null)
    {
        var existingSerial = exisitngEntry.Serial;
        verificationVoltage.Serial.Id = existingSerial.Id;
        verificationVoltage.Serial = new VerificationVoltageSerial()
        {
            Id = existingSerial.Id,
            Serial = existingSerial.Serial,
        };
    }

    var addedEntry = repository.Add(verificationVoltage); 
    await repository.SaveChanges().ConfigureAwait(false);
    return addedEntry;
}
public async Task<VerificationVoltage> GetBySerialNoTracking(string serialNumber)
{
    return await DbSet.Include(a => a.Serial)
                      .Where(a => a.Serial.Serial.Equals(serialNumber))
                      .OrderBy(a => a.VerificationVoltageSerialId)
                      .AsNoTracking()
                      .FirstOrDefaultAsync()
                      .ConfigureAwait(false);
}

My protected override void OnModelCreating(ModelBuilder modelBuilder) method, only repeats the attributes:

protected override void OnModelCreating(ModelBuilder modelBuilder)
{
    modelBuilder.Entity<ValidationLabAmbientMeasurements>()
                .HasOne(a => a.AmbientMeasurementsIdentifier)
                .WithMany();

    modelBuilder.Entity<VerificationVoltage>()
                .Property(a => a.Id)
                .ValueGeneratedOnAdd();

    modelBuilder.Entity<VerificationVoltage>()
                .HasOne(a => a.Serial)
                .WithMany(nameof(VerificationVoltage));

    modelBuilder.Entity<VerificationVoltage>()
                .HasMany(a => a.VerificationVoltageMeasurements)
                .WithOne(nameof(VerificationVoltage));
}

I have tried searching for answers, but my search queries do not get results on this specific issue.

question from:https://stackoverflow.com/questions/65933246/entity-framework-core-check-if-an-entity-part-of-a-one-to-many-relationship-exi

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)
Waitting for answers

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...