Database Context View Objects Not Working as Expec

2019-01-15 21:50发布

问题:

I am experiencing a very peculiar issue in my Code when using an Entity Framework View in MVC. I am only suspecting the problem to be attributed to the use of the View because I don't have the issue when using Tables.

My View is called LoadAuditStats_Report and the Controller Code for the Index is:

    private readonly RepositoryDBContext _repository = new RepositoryDBContext();
    public ActionResult Index()
    {
        var stats = _repository.LoadAuditStats_Report;

        return View(stats);
    }

An example of the data in the view would be:

If I examine the resulting output of the example from the Controller I will get 3 records but the data for all 3 records will be a repeat of the 1st record. So in this case, all 3 records will have the same field values of PackageAuditId 700.

This is really wierd because I've never seen this problem when using Tables so I have to wonder if there is some issue with EntityFramework4 interfacing with MVC3 when it relates to Views?

Should I refrain from the use of EntityFramework Views or is there something additional that I should be taking into consideration when working with them?

回答1:

A view also has a primary key in EF. If the key consists of field that are not really unique you can get duplicate rows in the result set. So you should investigate the view and decide what columns uniquely identify its rows and tell EF to use those columns as the primary key.