Skip to content

Commit

Permalink
Always scaffold [Key] attribute on all involved properties (#16682)
Browse files Browse the repository at this point in the history
Always scaffold [Key] attribute on all involved properties
when DataAnnotations have been requested.

fixes #15677
  • Loading branch information
ErikEJ authored and ajcvickers committed Jul 22, 2019
1 parent 9cc38f6 commit 0b101c5
Show file tree
Hide file tree
Showing 2 changed files with 48 additions and 13 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -231,20 +231,8 @@ protected virtual void GeneratePropertyDataAnnotations(
private void GenerateKeyAttribute(IProperty property)
{
var key = property.FindContainingPrimaryKey();
if (key?.Properties.Count == 1)
if (key != null)
{
if (key is IConventionKey concreteKey
&& key.Properties.SequenceEqual(KeyDiscoveryConvention.DiscoverKeyProperties(
concreteKey.DeclaringEntityType, concreteKey.DeclaringEntityType.GetProperties())))
{
return;
}

if (key.GetName() != key.GetDefaultName())
{
return;
}

_sb.AppendLine(new AttributeWriter(nameof(KeyAttribute)));
}
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -50,6 +50,7 @@ public Post()
Contributions = new HashSet<Contribution>();
}
[Key]
public int Id { get; set; }
public int? AuthorId { get; set; }
Expand All @@ -74,5 +75,51 @@ public Post()
Assert.Equal("TestNamespace.Contribution", contributionsNav.ForeignKey.DeclaringEntityType.Name);
});
}

[ConditionalFact]
public void Composite_key()
{
Test(
modelBuilder => modelBuilder
.Entity(
"Post",
x =>
{
x.Property<int>("Key");
x.Property<int>("Serial");
x.HasKey("Key", "Serial");
}),
new ModelCodeGenerationOptions
{
UseDataAnnotations = true
},
code =>
{
var postFile = code.AdditionalFiles.First(f => f.Path == "Post.cs");
Assert.Equal(
@"using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.ComponentModel.DataAnnotations.Schema;
namespace TestNamespace
{
public partial class Post
{
[Key]
public int Key { get; set; }
[Key]
public int Serial { get; set; }
}
}
",
postFile.Code);
},
model =>
{
var postType = model.FindEntityType("TestNamespace.Post");
Assert.NotNull(postType.FindPrimaryKey());
});
}
}
}

0 comments on commit 0b101c5

Please sign in to comment.