Entity Framework Type and Properties not mapping ( errors 11007 and 11009 )

593 views Asked by At

I'm having trouble with model first in entity framework 6, .net 4.7, visual studio 2017...

I'm trying to add a many to 0...1 with foreign key between two tables and when I try to validate the model I get an error saying the foreign key field in the table is not mapped. Furthermore, I cannot even add new entities to the model as I get an error on validation saying the entity is not mapped. What has it done to get itself into this state? I have barely used it to do anything.

What do I do to get it to do things without these errors? I know it's because it hasn't mapped things but it should do this automatically. The whole thing seems sloppy considering it's version 6.

Should I switch to Database first?

Thankyou.

1

There are 1 answers

1
Viktor Zimin On

for set relation many to 0...1 you must

1) Create models and add related entities in models

public class MainModel
{
    public MainModel()
    {
        ChildModels= new HashSet<ChildModel>();
    }

    public int Id { get; set; }

    public virtual ICollection<ChildModel> ChildModels{ get; set; }
}

public class ChildModel
{
    public int Id { get; set; }

    public int? MainModelId { get; set; }
    public MainModel MainModel { get; set; }
}

2) Set relation in Context class by FluentApi

modelBuilder.Entity<MainModel>()
            .HasMany(mm => mm.ChildModels)
            .WithOptional(cm => cm.MainModel )
            .HasForeignKey(cm => cm.MainModelId );

In one of this steps you may make mistake.

Database first is old approach and i don't advice you to use it.