Reputation: 147
I am aware of other questions on the same topic, however I have tried their solutions and none have worked for my code. I am configuring a one-to-many relationship with one Account with many JoinedClassIds.
Account.cs
public class Account {
// Actual account info
[Key]
public int _id { get; set; }
public string _name { get; set; }
public string _email { get; set; }
public ICollection<JoinedClassId> JoinedClasses { get; set; }
}
JoinedClassId.cs
[Keyless]
public class JoinedClassId {
public int classIdNumber { get; set; }
public Account Account { get; set; }
}
DBContext
public DbSet<Account> Accounts { get; set; }
public DbSet<JoinedClassId> JoinedClassIds { get; set; }
protected override void OnModelCreating(ModelBuilder modelBuilder) {
modelBuilder.Entity<Account>()
.HasMany(acc => acc.JoinedClasses)
.WithOne(jcid => jcid.Account);
modelBuilder.Entity<JoinedClassId>()
.HasOne(jc => jc.Account)
.WithMany(acc => acc.JoinedClasses);
modelBuilder.Entity<JoinedClassId>()
.HasNoKey();
}
I get the error
System.InvalidOperationException: 'Unable to determine the relationship represented by navigation 'Account.JoinedClasses' of type 'ICollection'. Either manually configure the relationship, or ignore this property using the '[NotMapped]' attribute or by using 'EntityTypeBuilder.Ignore' in 'OnModelCreating'.'
What can I do to fix this?
Upvotes: 1
Views: 2842
Reputation: 8338
Keyless
entities cannot participate in two way relationships. They can only contain reference navigation to other regular entities (entities with key). Also, regular entities cannot contain navigation properties to keyless entity types. What causing the issue in your case is, your Account
entity contains the navigation property JoinedClasses
, which is a collection of Keyless
entity.
For details - Keyless entity types characteristics
[Keyless]
attribute from JoinedClassId
entityclassIdNumber
property as keypublic class JoinedClassId
{
[Key]
public int Id { get; set; } // added key property
public int classIdNumber { get; set; }
public int AccountId { get; set; } // added foreign-key property
public Account Account { get; set; }
}
Then you can configure as -
protected override void OnModelCreating(ModelBuilder modelBuilder)
{
modelBuilder.Entity<Account>()
.HasMany(acc => acc.JoinedClasses)
.WithOne(jcid => jcid.Account)
.HasForeignKey(p=> p.AccountId); // if you have added a foreign-key property
}
Upvotes: 6
Reputation: 43860
Fix your classes:
public class Account {
[Key]
public int Id { get; set; }
public string Name { get; set; }
public string Email { get; set; }
public virtual ICollection<JoinedClass> JoinedClasses { get; set; }
}
public class JoinedClass {
[Key]
public int Id { get; set; }
public int ClassIdNumber { get; set; }
public int AccountId { get; set; }
public virtual Account Account { get; set; }
}
If you use EF Net5 , you don't need OnModelCreating fluent Api code. Delete all tables from db and migrate again
Upvotes: 0