Base solution for your next web application
Ends in:
01 DAYS
01 HRS
01 MIN
01 SEC
Open Closed

Help on Model migration generation: Wrong relation inferred #9118


User avatar
0
andyfuw created

Since we are not quick famimlar with EF Core, and encountered a weird situation, please kindly suggest on how we should deal with this.

By Power tools, We've created two entities: Customer and Contact, they have multiple relations here by design: one-to-many relation, which is one customer has many contacts, and one-to-one relation(not really one-to-one, but this how EF Core inferred), which is one customer must have one primary contact, the model class was generated as below after we added the navigation property on power tool:

Customer
{
        //Other properties here
        
    	public virtual Guid? PrimaryContactId { get; set; }
		
        [ForeignKey("PrimaryContactId")]
		public Contact PrimaryContactFk { get; set; }
}

Contact
{

    //Other properties here
    
    public virtual Guid? CustomerId { get; set; }
    
    [ForeignKey("CustomerId")]
    public Customer CustomerFk { get; set; }
}

after that, we've found EF Core migration generated a one-to-one relationship created unique index on Contact entity, ABPDbContextModelSnapshot.cs as below:

modelBuilder.Entity("xxx.Contact", b =>

    b.HasIndex("CustomerId")
            .IsUnique()
            .HasFilter("[CustomerId] IS NOT NULL");
                        
    //
    
     b.HasOne("FWT.ABP.MasterData.Customer", "CustomerFk")
            .WithOne()
            .HasForeignKey("FWT.ABP.MasterData.Contact", "CustomerId");
    

This is not expected, since this unique index will prevent we adding multiple contacts under one customer, could you please kindly guide us how to deal with this senario? I thought we should manally change this EF core implicit inferring behavior, but just don't know where we should carry out the changes and how? by EF data anotation on the model class or by using Fluent API makes change in DbContext's OnModelCreating() method?

by the way, we've been using Power tools v2.3, and ASP.NET Core MVC + JQuery, v7.2

Thanks in advance.


2 Answer(s)
  • User Avatar
    0
    ismcagdas created
    Support Team

    Hi,

    You can use an approach like this https://stackoverflow.com/a/38528029 for adding List<Contact> to your customer entity.

  • User Avatar
    0
    andyfuw created

    Thank you for the help @ismcagdas

    We've solved this by adding

    [InverseProperty("CustomerFk")]
    public List<Contact> Contacts  { get; set; }
    

    to Customer model class. after generated the new migration, the unique index on Contact has been removed which is expected.