Entity Framework 1-to-1 relationship with ASP.NET Boilerplate

asp.net-boilerplate asp.net-mvc-5 c# ef-code-first entity-framework-6

Question

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; }
}
1
2
4/6/2018 3:57:00 PM

Accepted Answer

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

1
9/1/2016 8:45:18 AM

Popular Answer

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.



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