Alexandr Sulimov
Alexandr Sulimov

Reputation: 1924

EntityFramework 6 DatabaseFirst add navigation property from code

I have (can`t change) EF DataBase first project without navigation property in models.

I want extend autogenerated models and add navigation property

  1. Generated model
//generated.cs

public partial class company
{
    public int id { get; set; }
    public string name { get; set; }
}

public partial class user
{
    public int id { get; set; }
    public int company_id { get; set; }
}
  1. I want add navigation property from code
//model_extension.cs

public partial class user
{
    public company Company { get; set; }
}

I have exception "The specified type member 'Company' is not supported in LINQ to Entities. Only initializers, entity members, and entity navigation properties are supported."

I work with CodeFirst before.

I understand, I must link user.company_id to Company But not understand how make this with code (not designer)

Upvotes: 0

Views: 972

Answers (1)

Masoud Andalibi
Masoud Andalibi

Reputation: 3228

In Database First Approach, You are generating your POCO objects from database schema via Entity Framework Designer/ADO.NET Entity Data Model so it is not flexible as Code-First, you need to go on database, and change the schema yourself and update your .edmx file. while adding properties to these Models are possible in c# side, but they are not going to be added to your database schema,

I suggest your reverse your database schema and go as Code-First Approach, This nuget package can do this for you.

After Reversing It's all about Code-First then, creating your own DbContext and OnModelCreating and let the Migration handle the rest. Then you can use Eager Loading of EF to load your data,

Upvotes: 1

Related Questions