How to set custom name of ICollection property in automatically generated POCO entity, using Entity Framework

170 views Asked by At

Let’s say there are two tables in database:

User 
int UserId 
string Name

Task 
int TaskId 
string Description 
int TaskCreatorId 
int TaskAssigneeId

and two Foreign Keys are defined between Task and User: TaskCreatorId – UserId and TaskAssigneeId - UserId

I already have database, and use "database first" approach. Using Code Generation in Entity Framework, two POCO classes are automatically created:

User.cs

public int UserId
public string Name
public ICollection<Task> Tasks
public ICollection<Task> Tasks1

Task.cs

public int TaskId
public string Description
public int TaskCreatorId
public int TaskAssigneeId
public User User
public User User1

In order to have meaningful entities, I have to change:

public ICollection<Task> Tasks  --> public ICollection<Task> CreatedTasks  
public ICollection<Task> Tasks1 --> public ICollection<Task> AssignedTaska

and

public User User  --> public User TaskCreator
public User User1 --> public User TaskAssignee

If I go to Model.edmx and make changes in Model Browser –> Associations and set needed mapping, it is overwritten after first update from database.

How to do this?

2

There are 2 answers

0
tintyethan On

Are you familiar with view models? You can create classes that represent you entities in different ways to suite your needs.

So you would create new folder called viewmodels, create a new class with an appropriate name, and add you members there - TaskCreator, TaskAssignee, etc. Its a very common, standard design pattern.

You can just search viewmodel, or here's something to get you started...

http://www.markwithall.com/programming/2013/03/01/worlds-simplest-csharp-wpf-mvvm-example.html

0
Etienne Maheu On

In an EDMX, the association is the mapping between the property and the database column. If you change this mapping, you change which column the property is linked to. What you want to do is change the property name instead and keep the same association.