I have the following:
public abstract class EntityBase
{
[Key]
public int Id { get; set; }
public DateTime? CreatedTime { get; set; }
public DateTime? ModifiedTime { get; set; }
}
public class AnalysisFile : EntityBase
{
public AnalysisFile()
{
DateAdded = DateTime.Now;
}
public string SourceFolder { get; set; }
public string Filename { get; set; }
public DateTime DateAdded { get; set; }
public long FileSize { get; set; }
public Document Document { get; set; }
}
public class Document : EntityBase
{
public Document()
{
Publish = true;
}
public string Name { get; set; }
public int AreaId { get; set; }
public int SchoolId { get; set; }
public int Year { get; set; }
public long FileSize { get; set; }
public AnalysisFile AnalysisFile { get; set; }
public School School { get; set; }
public Area Area { get; set; }
public bool Publish { get; set; }
}
modelBuilder.Entity<Document>().HasRequired(x => x.AnalysisFile);
modelBuilder.Entity<AnalysisFile>().HasOptional(x => x.Document);
My issue is that EF does not appear to create a foreign key for the relationship between AnalysisFile and Document, am I missing something here or is this the expected behavior?
I have also tried creating AnalysisFileId and DocumentId properties on both classes but when I do that they don’t get populated with any ids.
Another question also: how can I ensure that Document has cascade-deletion against AnalysisFile?
One-to-one relationships with Entity Framework are Shared Primary Key Associations. They don’t have a separate foreign key column aside from the primary key because the primary key in
Documentis the foreign key toAnalysisFileat the same time. (You can see that when you inspect the relationship created in the database. It should relate the foreign keyIdinDocumentwith the primary keyIdinAnalysisFile.)You can enable cascading delete like so: