简体   繁体   中英

Entity Framework Not Recognizing Foreign Key?

I'm trying to set a variable like so...

var userID = WebMatrix.WebData.WebSecurity.CurrentUserId;
var options = db.UserProfiles.Find(userID).TaskTypeSetting;

I'm using the user authentication table provided by the basic Internet Application template.

Row UserId in table UserProfile has a one-to-many relationship with row User in table TaskTypeSetting .

It is telling me that it cannot find a definition for TaskTypeSetting . Shouldn't I be able to do this if my relationships are set up properly?

Here is the model for the table:

namespace DailyTaskList.Models
{
    using System;
    using System.Collections.Generic;

    public partial class TaskTypeSetting
    {
        public int ID { get; set; }
        public int Type { get; set; }
        public int User { get; set; }
    }
}

It looks like it's not adding the relationship to the code? The .edmx diagram shows the relationships as I have them set up.

Edit:

UserProfile class definition:

namespace DailyTaskList.Models
{
    using System;
    using System.Collections.Generic;

    public partial class UserProfile
    {
        public int UserId { get; set; }
        public string UserName { get; set; }
    }
}

Compiler Error Message: CS1061: 'DailyTaskList.Models.UserProfile' does not contain a definition for 'TaskSetting' and no extension method 'TaskSetting' accepting a first argument of type 'DailyTaskList.Models.UserProfile' could be found (are you missing a using directive or an assembly reference?)

I'm also getting this under Mapping Details:

Mappings are not allowed for an association over exposed foreign keys.

After some research, I've discovered that what I was experiencing was a bug with Visual Studio 2012 and Entity Framework. Entity Framework was failing to generate my code properly. This is caused by the .edmx file being nested within the project files.

The solution I used:

  • Right click on .tt file and select "Run Custom Tool"

Other solutions:

  • Update Visual Studios.
  • Drag .edmx out of the project folder.

I wrote a blog on the situation which can be found here .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM