I have two collections. The parent has many children, but also stores the most current child's id.
public class Foo
{
public int Id { get; set; }
public ICollection<Bar> Bars { get; set; }
public int? CurrentBarId { get; set; }
// adding this causes the error below
public virtual CurrentBar CurrentBar { get; set; }
}
public class Bar
{
public int Id { get; set; }
public int FooId { get; set; }
public virtual Foo Foo { get; set; }
}
When I add the CurrentBarId property everything is persisted correctly. However, when I add the CurrentBar property an exception is thrown when the Bar is created.
I get the exception:
{"Invalid column name 'Foo_Id'."}
How can I map this navigation property in the context?
Update
I have played around with this a bit and ended up with:
modelBuilder.Entity<Foo>()
.HasOptional(x => x.CurrentBar)
.WithOptionalDependent()
.Map(map =>
{
map.ToTable("Bar").MapKey("CurrentBarId");
});
Now I get the following error. Is this in the right direction, or how should I be trying to do this?
error 3034: Problem in mapping fragments starting at lines 213, 442:An entity from one EntitySet is mapped to a row that is also mapped to an entity from another EntitySet with possibly different key. Ensure these two mapping fragments do not map two unrelated EntitySets to two overlapping groups of rows.
Assuming that Foo.Bars
and Bar.Foo
are the ends of the same relationship and that CurrentBar
is one end of a second relationship, I would try this:
modelBuilder.Entity<Foo>()
.HasMany(f => f.Bars)
.WithRequired(b => b.Foo)
.HasForeignKey(b => b.FooId)
.WillCascadeOnDelete(false);
modelBuilder.Entity<Foo>()
.HasOptional(f => f.CurrentBar)
.WithMany()
.HasForeignKey(f => f.CurrentBarId)
.WillCascadeOnDelete(false);
This will create a (nullable) CurrentBarId
FK column in the Foos
table and a (not nullable) FooId
FK column in the Bars
table.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.