Reputation: 29
Let's have two entities:
public class Function
{
public int Id {get;set;}
[Required]
public virtual FunctionConfiguration FunctionConfiguration {get;set;}
}
public class FunctionConfiguration
{
public int Id {get;set;}
[ForeignKey("FunctionId")]
public virtual Function Function {get;set;}
}
And here is my current configuration:
builder
.HasOne(v => v.Function)
.WithOne(f => f.FunctionConfiguration)
.IsRequired()
.OnDelete(DeleteBehavior.Cascade);
Now I want to get rid of [ForeignKey("FunctionId")]
attribute and update my configuration like this:
builder
.HasOne(v => v.Function)
.WithOne(f => f.FunctionConfiguration)
.IsRequired()
.HasForeignKey("FunctionId")
.OnDelete(DeleteBehavior.Cascade);
So my entity class will be free of having DB attributes.
When I try to test my schema by creating new migration I get following error:
You are configuring a relationship between 'FunctionConfiguration' and 'Function' but have specified a foreign key on 'FunctionId'. The foreign key must be defined on a type that is part of the relationship.
What I'm doing wrong? Why can't I just use "FunctionId"
string in the same way as for ForeignKey
attribute?
Please don't answer with "Add FunctionId
to FunctionConfiguration
class" - I don't want to have such property in my class.
Thanks.
Upvotes: 0
Views: 849
Reputation: 631
Because as the documentation states the first parameter of this method takes the name of the dependent entity type and not the name of the foreign key you want to produce. So your code should look like this .HasForeignKey(typeof(FunctionConfiguration), "FunctionId")
.
Upvotes: 2