开发者

MVC 2 with Entity Data Model returning Null for foreign keys

开发者 https://www.devze.com 2023-02-23 13:29 出处:网络
I am creating my first MVC 2 applicaiton. I\'ve followed expamples in the books I have and created an ADO.NET Entity Data Model that auto generated the model.edms and model.designer.cs files. I then c

I am creating my first MVC 2 applicaiton. I've followed expamples in the books I have and created an ADO.NET Entity Data Model that auto generated the model.edms and model.designer.cs files. I then created a repository.cs file in my model folder to store my methods for retrieving data. When I use theses methods to retrieve an object from my tables the foriegn key attributes are returned null. Here is one of my methods

    private LanTracerEntities2 entities = new LanTracerEntities2();

    public Employee FindEmployee(string empId)

  开发者_运维问答  {
        var emp =  from employee in entities.Employees
               where employee.LogIn == empId
               select employee;

        return emp.FirstOrDefault();
    }

The employee table has the following columns: ID EmpFName EmpLName EmpInitial Phone LogIn Email LocID

LocID is a foriegn key linking it to the Location table. When I run the method it returns a value for every attribute but LocID. LocID is null. There is data in the table. This is not the only object I have that is returning null for foriegn key attributes. How can I get the method to return the FK values?


It looks like you are comparing with the wrong property? Given the name of your parameter I think you might want to compare with the Id of the employee:

    var emp =  from employee in entities.Employees
           where employee.ID == empId
           select employee;

Having said that your primary key should be numeric int/bigint - if that's the case do this instead:

    int id = Convert.ToInt32(empId);
    var emp =  from employee in entities.Employees
           where employee.ID == id
           select employee;

If you want to include Location as part of your query results you can specifically ask for that:

var emp =  from employee in entities.Employees.Include("Location") 
           ..

This should populate the Location property in your employee record when you retrieve it.

0

精彩评论

暂无评论...
验证码 换一张
取 消