Using [Key] attribute on properties used in composite primary keys defined with Fluent API will create extra foreign keys and indexes in table
Consider the following code-first entities:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.EntityFrameworkCore;
using System.ComponentModel.DataAnnotations;
using System.ComponentModel.DataAnnotations.Schema;
namespace EntityFramework7Exploration
{
public class BloggingContext: DbContext
{
public DbSet<Blog> Blogs { get; set; }
public DbSet<Post> Posts { get; set; }
public DbSet<BlogPost> BlogPosts { get; set; }
protected override void OnModelCreating(ModelBuilder modelBuilder)
{
modelBuilder.Entity<BlogPost>()
.HasKey(k => new { k.BlogId, k.PostId });
}
}
public class Blog
{
public Guid BlogId { get; set; }
public string Url { get; set; }
}
public class Post
{
public Guid PostId { get; set; }
public string Title { get; set; }
public string Content { get; set; }
}
public class BlogPost
{
[Key]
public Guid BlogId { get; set; }
public Blog Blog { get; set; }
[Key]
public Guid PostId { get; set; }
public Post Post { get; set; }
}
}
This will create a BlogPost table containing the following fields in SQL Server:
BlogId (PK, uniqueidentifier, not null)
PostId (PK, uniqueidentifier, not null)
BlogId1 (FK, uniqueidentifier, null)
BlogId2 (FK, uniqueidentifier, null)
Removing the [Key] attributes will resolve the issue and BlogId and PostId will be the only fields created (as expected). Also, adding [Key, Column(Order =1)] and [Key, Column(Order=2)] will result in the same behaviour creating the extra Foreign Keys.
Other details:
Visual Studio 2015 Update 3 Net Core 1.0.0 Console Application
Project.json:
{
"version": "1.0.0-*",
"buildOptions": {
"emitEntryPoint": true
},
"dependencies": {
"Microsoft.EntityFrameworkCore": "1.0.0",
"Microsoft.EntityFrameworkCore.SqlServer": "1.0.0",
"Microsoft.EntityFrameworkCore.Tools": "1.0.0-preview2-final",
"Microsoft.NETCore.App": {
"type": "platform",
"version": "1.0.0"
}
},
"frameworks": {
"netcoreapp1.0": {
"imports": "dnxcore50"
}
},
"tools": {
"Microsoft.EntityFrameworkCore.Tools": "1.0.0-preview2-final"
}
}
@treierts we believe this is a duplicate report of #5769 which we fixed for 1.1.
If you would like to test a build containing the fix you can install a nightly build for EF Core from for the dev branch (more information on the various feeds in https://github.com/aspnet/Home/wiki/NuGet-feeds).
Closing as duplicate for now, but feel free to re-open if the fix doesn't work for your scenario.