Reputation: 1116
Struggling on a Foreign key with Entity Framework (1 to many relationship).
class1:
public partial class Class1
{
public int Id { get; set; }
[ForeignKey("Class2_Id")]
public Class2 Class2{ get; set; }
...}
Class2:
public partial class Class2
{
public int Id { get; set; }
public virtual ICollection<Class1> Stuff{ get; set; }
...}
1)I tried with fluentAPI: 1st try:
modelBuilder.Entity<Class2>().HasMany<Class1>(p => p.Stuff).WithOptional().Map(m => m.MapKey("Class2_Id")).WillCascadeOnDelete();
2nd try:
modelBuilder.Entity<Class1>().HasRequired(i => i.Class2).WithMany().Map(m => m.MapKey("Class2_Id"));
2)without fluentAPI:
I declared the concerned Class2
field this way:
[Column("Class2")]
public int Id { get; set; }
Even (which probably makes no sense):
[ForeignKey("Class2")]
public int Id { get; set; }
I always get this error:
The ForeignKeyAttribute on property 'Class2' on type 'Class1' is not valid. The foreign key name 'Class2_Id' was not found on the dependent type 'Class1'. The Name value should be a comma separated list of foreign key property names.
Any idea what is wrong?
thx in advance.
Upvotes: 1
Views: 363
Reputation: 39376
With your fluent api configurations you are defining a unidirectional relationship, so the correct way would be:
modelBuilder.Entity<Class2>().HasMany(p => p.Stuff)
.WithOptional(c=>c.Class2)
.Map(m => m.MapKey("Class2_Id"))
.WillCascadeOnDelete();
MapKey
method is used when you don't want to have the foreign key as a property in your model class.
Use ForeignKey
attribute when you represent the FK column as a property of your entity:
public partial class Class1
{
public int Id { get; set; }
public int? Class2_Id{ get; set; }
[ForeignKey("Class2_Id")]
public Class2 Class2{ get; set; }
}
In this last case your relationship configuration using Fluent Api would be:
modelBuilder.Entity<Class2>().HasMany(p => p.Stuff)
.WithOptional(c=>c.Class2)
.HasForeignKey(c=>c.Class2_Id))
.WillCascadeOnDelete();
Upvotes: 1