E. Jaep
E. Jaep

Reputation: 2143

Adding relations in code only

Given that:

typically, we do have a users table with id, name... and a transaction table with id, user_id, amount... As there is no relation at the DB level, Entity Framework does not relates the objects together and there is no way to use constructs like:

transactions.Select(t=> new {t.id, t.user.name, t.amount})

Is there a way to manually add the relationship in the Entity Framework (model first) so we can leverage Linq?

Upvotes: 3

Views: 111

Answers (2)

Oliver
Oliver

Reputation: 45081

Normally all the classes generated with the Entity Framework are partial. This means you can add to the project a second .cs file where you can add the same class (within the same namespace) and add your own methods to it. There you could add your own AddRelationsToDataSet() method, which won't be touched if you make any changes through the designer on your model.

The only drawback is, that you have to manually call this method each and everywhere after the constructor. Or you create a static Create() method within your partial class part that calls the constructor and afterwards your method. Then you simply have to check that nobody calls the constructor directly but only through your creator method.

Upvotes: 0

Oliver
Oliver

Reputation: 9002

Yes it it possible.

Model first

In the edmx designer, right click > Add New > Association. You'll get a dialog to set up the relationship between the two models:

enter image description here

Code first

Something similar to the following model setup should work, even without relationships present on the database:

public class User
{
    public int UserId { get; set; }

    [ForeignKey("UserId")]
    public virtual ICollection<Transaction> Transactions { get; set; }
}

public class Transaction
{
    public int TransactionId { get; set; }

    [ForeignKey("User")]
    public int UserId { get; set; }

    public User User { get; set; }
}

When your models are setup in this way, the following LINQ:

transactions.Select(t=> new {t.id, t.user.name, t.amount});

Should then be possible, and will be converted nicely into SQL by EF when running.

Upvotes: 1

Related Questions