2

How to set 1:1 relationship with the below-mentioned models when we use ASP.NET Boilerplate? Thanks in advance.

Note 1: I have seen this nice answer about the EF 1-to-1 relationship. But unfortunately, I don't know how to set it with ASP.NET Boilerplate because PK is automatically set by ABP. In my scenario, both tables have int PK.

Note 2: Here, the Property and Address models have 1:1 relationship.

Property model:

[Table("IpProperties")]
public class Property : FullAuditedEntity
{
    public virtual bool Vacant { get; set; }

    public virtual Address Address { get; set; }
}

Address model:

[Table("IpAddresses")]
public class Address : FullAuditedEntity
{ 
    [Required]
    [MaxLength(MaxLength)]
    public virtual string StreetNumber { get; set; }

    public virtual Property Property { get; set; }
}
aaron
  • 17,311
  • 4
  • 27
  • 63
Sampath
  • 50,641
  • 40
  • 250
  • 357

2 Answers2

3

Relationship mapping should be done in the OnModelCreating method of your DbContext. Your DbContext class will be in the EntityFramework project under the EntityFramework folder.

You can use something like the following:

protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
    base.OnModelCreating(modelBuilder);
    modelBuilder.Entity<Property>().HasRequired(e => e.Address).WithOptional(e => e.Property);
}

If the Property property of the Address should not be null, the .WithOptional() method can be replaced with WithRequiredDependent() or WithRequiredPrincipal(), depending on the use case.

Another Solution :

ABP forum - REFERENTIAL INTEGRITY ISSUE - ONE TO ONE RELATIONSHIP

Jacques Snyman
  • 3,699
  • 1
  • 23
  • 44
0

You will not find an HasOptional equivalent method in EF7. By convention if your FK property is nullable, you navigation property will be treated as optional

 modelBuilder.Entity<Blog>()
                .HasOne(p => p.Document)
                .WithOne(i => i.CancelNote)
                .HasForeignKey<Document>(b => b.CancelNoteForeignKey);

About your second question,EF Core (EF7) doesn't support Lazy Loading. In this link you will find the options you have now to load related entities

PS: please use your own entity names.