What is the best way to check if related entity exists in EntityFramework

c# entity-framework entity-framework-core

Question

I have two entities with one-to-zero-or-one relation: Version and ChangeLog. The second one stores file with changelog (for example 'ReadMe.html').

public class Version 
{
    [Key]
    public int Id { get; set; }
    public string Name { get; set; }
    public ChangeLog ChangeLog { get; set; }
}

public class ChangeLog 
{
    [Key]
    public int Id { get; set; }
    public string FileName { get; set; }
    public byte[] File { get; set; }

    public int VersionId { get; set; }
    public Version Version { get; set; }
}

Code for one-to-one relation:

modelBuilder.Entity<Version>()
            .HasOne(v => v.ChangeLog)
            .WithOne(c => c.Version)
            .HasForeignKey<ChangeLog>(c => c.VersionId);

How to check if related entity exists. So for the one-to-many relation I could do things like this Product.Versions.Any(). What about one-to-one? Should I use a context context.ChangeLogs.Any(c => c.VersionId == versionId)?

1
0
8/24/2016 7:27:41 AM

Popular Answer

You can do this by doing the following:

  1. when you query for the 'Version' entity, ensure you also request the 'ChangeLog' entity, as follows.

    var versionWithChangeLog = context.Versions.Include(v => v.ChangeLog)
                                      .FirstOrDefault(v => v.Id == versionid);
    
  2. this ensures that EF always tries to pull the related ChangeLog entity for the Version entity.

  3. now do a null check on the related ChangeLog entity.

     if (versionWithChangeLog && versionWithChangeLog.ChangeLog != null)
     {
        // we got  a version entity with a changelog.
     }
    

basically if there is a related record, EF will always pull it, since we asked it to. And if it is null, that means the database did not have a record.

Ohh, and if you want to just check if the related changelog entity exists or not, and not retrieve it, you can use these:

var versionsWithChangeLog = context.Versions.Where(v => v.ChangeLog != null);

var versionsWithoutChangeLog = context.Versions.Where(v => v.ChangeLog == null);
0
8/24/2016 8:33:24 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