I have these two classes:
public class Foo
{
[Key]
public int Id { get; set; }
public string Name { get; set; }
// ...
// Foo has N bars, 1 of which is primary
[ForeignKey("Bar")]
public int? PrimaryBarId { get; set; }
public virtual Bar PrimaryBar { get; set; }
}
public class Bar {
[Key]
public int Id { get; set; }
public string Name { get; set; }
// ...
// Foo -> Bar == 1:N
[ForeignKey("Foo")]
public int FooId { get; set; }
public virtual Foo Foo { get; set; }
}
EF now expects me to create a property BarId
and Bar
on Foo
but I don't want that. I want the property to be named PrimaryBar. I have a 1:N relationship on Foo
->Bar
which is reflected elsewhere and not of interest for this question.
EF keeps telling me:
The ForeignKeyAttribute on property 'PrimaryBarId' on type 'X.y.Foo' is not valid. The navigation property 'Bar' was not found on the dependent type 'X.y.Foo'. The Name value should be a valid navigation property name.
How do I convince EF to use the PrimaryBar
(and PrimaryBarId
) properties (preferrably with an attribute, although using the DbModelBuilder
in the OnModelCreating
override is an option too?
EDIT
Figured it out. I was missing a:
public virtual ICollection<Bar> Bar { get; set; }
on my Foo
class. See here for the explanation.
[ForeignKey("PrimaryBar")]
on Foo.PrimaryBarId ? I think the exception message is inconsistent with the classes you provided, did you edit them before posting?PrimaryBar
of typeNumber
instead of typeBar
?One or more validation errors were detected during model generation: Foo_PrimaryBar_Target: : Multiplicity is not valid in Role 'Foo_PrimaryBar_Target' in relationship 'Foo_PrimaryBar'. Because the Dependent Role properties are not the key properties, the upper bound of the multiplicity of the Dependent Role must be '*'.
I just want a 0..1 onFoo
toBar
.