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)
?
You can do this by doing the following:
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);
this ensures that EF always tries to pull the related ChangeLog
entity for the Version
entity.
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);