Sornii
Sornii

Reputation: 421

One-to-many relation in ASP.NET MVC4 and CodeFirst

I'm having some problems with relationship over ASP.NET MVC4 and the CodeFirst, also with returning values with these tables which are related with foreign key.

First of all, let's see if I'm doing it correctly.

Here's a example of my code:

Person Class

public class Person {
    public int Id { get; set; }
    public string Name { get; set; }
    public string Surname { get; set; }
    public City City { get; set; }
}

City Class

public class City {
    public int Id { get; set; }
    public string Name { get; set; }
}

So, with this, the database created a nice looking relationship, and it seens to work very well. I have after this code, tables like this:

Person
--Id (PK)
--Name
--Surname
--City_Id (FK)

City
--Id (PK)
--Name

I've populated this with a seed, here's a example:

context.Person.AddOrUpdate(p => p.Name,
    new Person { Name = "Me", City = new City { Name = "Ludlow" } }
);

And when I need to retrieve the information to a view, like this...

MyDataBase.cs

public class LeilaoDb : DbContext
{
    public DbSet<Person> Persons { get; set; }
    public DbSet<City> Cities { get; set; }
}

HomeController.cs

MyDataBase _db = new MyDataBase();

        public ActionResult Index()
        {
            var model = _db.Persons.ToList();

            return View(model);
        }

Home/Index.cshtml

@model IEnumerable<testingproject.Models.Person>

@{
    ViewBag.Title = "Home Page";
}

@foreach (var item in Model)
{
    @Html.Partial( "_Person", item );
}

_Person.cshtml

@model testingproject.Models.Person

<div>
    <h3>@Model.Name</h3>
    @Model.City.Name
</div>

I receive a null exception...

Object reference not set to an instance of an object.

Description: An unhandled exception occurred during the execution of the current web request. Please review the stack trace for more information about the error and where it originated in the code. 

Exception Details: System.NullReferenceException: Object reference not set to an instance of an object.

So, what's wrong?

Solution:

I found the solution,

MyDataBase _db = new MyDataBase();

public ActionResult Index()
{
    var model = _db.Persons.ToList();

    return View(model);
}

This code retrieves only the Persons, maybe to not overload when it's not necessary to do relationships. You need to specify when need to do these relationships with a Include() method.

After this, is simple:

MyDataBase _db = new MyDataBase();

public ActionResult Index()
{
    var model = _db.Persons.Include("City");

    return View(model);
}

I feel strange passing a string to this method, but it's ok. I now can return my values with @Model.City.Name if I really need.

I found the solution in this website here

Upvotes: 3

Views: 1971

Answers (1)

Sornii
Sornii

Reputation: 421

The entitity framework does not do relationships unnecessary. If you want to include others table you need to call a method or make the properties as virtual to do a lazy relationship.

public virtual City City { get; set; }

this way, lazy mode is made.

var model = _db.Persons.Include("City").ToList();

and this way is the method to manualy include the relationship tables when necessary.

If you want to just call a person and not doing the join just call _db.Persons.ToList();

Upvotes: 1

Related Questions