How to use schema name in EF core autogenerated names?

Paweł Kieliszek 5 Reputation points
2023-12-27T11:07:55.9633333+00:00

Hi,

I am migrating my project from EntityFramework to EntityFramework Core.

What I noticed EF Core has different name convention.

When I am generating new migration it is not including schema name.

For example, let say Car class will have foreign key to Manufacturer:

class Car()

{

int ManufacturerId get; set;

}

And now result will be following:

  • ef - FK_dbo.ManufacturerID
  • ef core - FK_ManufacturerId

How to force EF Core to produce FK name with same patter as EF.

Thanks

Developer technologies | .NET | Entity Framework Core
Developer technologies | C#
Developer technologies | C#
An object-oriented and type-safe programming language that has its roots in the C family of languages and includes support for component-oriented programming.
0 comments No comments
{count} votes

3 answers

Sort by: Most helpful
  1. Paweł Kieliszek 5 Reputation points
    2024-01-02T08:57:28.2966667+00:00

    Let say I find kind of solution which maybe doesn't look nice, however it works.

    On OnModelCreating I am going through all keys and modify them:

    foreach (var entityType in modelBuilder.Model.GetEntityTypes())             
    {                 
    	var fks = entityType.GetForeignKeys().ToList();                 
    	foreach (var f in fks)                 
    	{
    	    var n = f.GetConstraintName();                     
    		if(n == null)                         
    			continue;                      
    
    		if (!n.ToLower().Contains("dbo"))                     
    		{                         
    			char targetChar = '_';                          
    			var positions = n.Select((c, i) => c == targetChar ? i : -1)
    							 .Where(i => i != -1).ToList();                          
    
    			if (positions.Any() && positions.Count > 1)                         
    			{                             
    				var newName = n.Insert(positions[1]+1, "dbo.");                             
    				newName = newName.Insert(positions[0]+1, "dbo.");
    				f.SetConstraintName(newName);                         
    			}                     
    		}                 
    	}             
    }
    
    1 person found this answer helpful.
    0 comments No comments

  2. Wenbin Geng 746 Reputation points Microsoft External Staff
    2023-12-28T09:45:18.6533333+00:00

    Hi @Paweł Kieliszek, Welcome to Microsoft Q&A.

    In Entity Framework (EF) 6 and earlier versions, the default naming convention for foreign key constraints is <tablename>_<primarykeypropertyname>. However, Entity Framework Core (EF Core) uses a more simplified naming convention by default.

    If you want to customize the naming conventions in EF Core to match the patterns used in EF 6, you can do so by overriding the default conventions.

    Here's how you can achieve this:

    Use Fluent API to Configure the Naming Conventions:

    You can use the Fluent API in the OnModelCreating method of your DbContext to configure the naming conventions.

    protected override void OnModelCreating(ModelBuilder modelBuilder)
    {
        modelBuilder.Entity<Car>()
            .HasOne(c => c.Manufacturer)
            .WithMany() // Assuming you have a navigation property for Manufacturer
            .HasForeignKey(c => c.ManufacturerId)
            .HasConstraintName("FK_dbo.ManufacturerID"); // This sets the FK constraint name
    }
    

    This will explicitly set the foreign key constraint name to FK_dbo.ManufacturerID.

    Use Data Annotations:

    Alternatively, you can also use data annotations to specify the foreign key constraint name directly on the navigation property:

    [ForeignKey("ManufacturerId", Name = "FK_dbo.ManufacturerID")]
    public int ManufacturerId { get; set; }
    

    However, using data annotations for this purpose may not be as flexible or clear as using the Fluent API.

    Best Regards,

    Wenbin


    If the answer is helpful, please click "Accept Answer" and upvote it.

    Note: Please follow the steps in our documentation to enable e-mail notifications if you want to receive the related email notification for this thread.


  3. Morad Aziz 80 Reputation points
    2023-12-27T11:57:42.8033333+00:00

    You could use data annotation

    [Column("FK_dbo.ManufacturerID")]  
    public GUID FK_ManufacturerId { get; set; }
    

Your answer

Answers can be marked as 'Accepted' by the question author and 'Recommended' by moderators, which helps users know the answer solved the author's problem.