-
Notifications
You must be signed in to change notification settings - Fork 3.2k
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Improve exception when defining a relationship to a keyless entity type #20292
Comments
@seattleite7 What is your intention by using |
@ajcvickers I was going off the error message "The type requires a primary key to be defined. If you intend to use a keyless type, call HasNoKey()". But now I get it has to have a primary key even if the foreign key is unique. Full disclosure, I am very new to EF. |
@seattleite7 Welcome to EF Core! :-) There's a few ways that you could map these types. Taking the lead from your code, something like this will map the types as normal entity types: protected override void OnModelCreating(ModelBuilder builder)
{
builder.Entity<ContactInfo>().HasKey(e => e.UserID);
builder.Entity<ContactInfo>().ToTable("contacts");
builder.Entity<Summary>().HasKey(e => e.UserID);
builder.Entity<Summary>()
.HasOne(e => e.Contact)
.WithOne()
.HasPrincipalKey<Summary>(e => e.UserID)
.HasForeignKey<ContactInfo>(b => b.UserID);
builder.Entity<Summary>().ToTable("summaries");
} When writing a query against this, you'll need to use var query = context.Summaries.Include(e => e.Contact).Where(e => e.UserID == 1); Another option would be to use an owned type. This is more appropriate if the ContactInfo entity is conceptually part of the
Note that in either case, this code is problematic: public ContactInfo Contact { get; set; } = new ContactInfo(); This creates a new ContactInfo entity instance every time a Summary is created, which in turn leads to ambiguity if EF loads an entity instance. See #18007 for an in-depth discussion/ |
Duplicate of #18149 |
Further technical details
EF Core version: Microsoft.EntityFrameworkCore 3.1.2
Database provider: Pomelo.EntityFrameworkCore.MySql 3.1.1
Target framework: .NET Core 3.1.0
Operating system: Windows 10
IDE: Microsoft Visual Studio Community 2019 Version 16.4.2
The text was updated successfully, but these errors were encountered: