Posting Questions
Posting Questions

Reputation: 217

Why entity framework is referencing a column that doesn't even exist?

My project is throwing error

Invalid column name 'InitialsID_InitialsID'.

public User ValidateUser(string Username, string Password)
{
    return uow.UserRepository.GetQueryable().Where(x => x.UserName == Username && x.Password == Password).FirstOrDefault();
}

Even there's no column by that name in the whole solution.

I had generated a migration script and it had that name in it but I changed that to InitialsID but still it asks for the same name.

How do I resolve it? I tried putting ForeignKey attribute etc but nothing works.

User.cs

public class User
{
    public int UserID { get; set; }
    public int UserGroupID { get; set; }
    public UserGroup UserGroup { get; set; }
    public string UserName { get; set; }
    public string FullName { get; set; }
    public string Email { get; set; }
    public string Designation { get; set; }
    public string Password { get; set; }
    public bool? PasswordExpire { get; set; }
    public DateTime? ExpiryDate { get; set; }
    public bool Status { get; set; }
    public DateTime? CreatedOn { get; set; }
    public string CreatedBy { get; set; }
    public DateTime? ModifiedOn { get; set; }
    public string ModifiedBy { get; set; }

    public string Office { get; set; }

    public string Station { get; set; }

    public Initials InitialsID { get; set; }
}

Initials.cs

public class Initials
{
    public short InitialsID { get; set; }
    public string Code { get; set; }
}

I am using Code First approach.

Upvotes: 1

Views: 63

Answers (2)

TanvirArjel
TanvirArjel

Reputation: 32109

Problem is in your foreign key configuration. When you are referencing navigation property public Initials InitialsID { get; set; }, EF is adding an implicit foreign key for this navigation property and it is by convention navigationPropery_navigationPropertyPrimaryKey and hence it is InitialsID_InitialsID

If you really want public Initials Initials { get; set; } navigaation property in User model class then write your foreign key configuration as follows:

public class User
{
    public int UserID { get; set; }
    public int UserGroupID { get; set; }

    ......................

    public short InitialsId { get; set; }
    public Initials Initials { get; set; }
}

Upvotes: 2

isaeid
isaeid

Reputation: 553

It seems your database not migrated with new model or new models property, Pleas migrate your database. If you are using dotnet core, in cmd on the project folder type:

dotnet ef migrations add [name]

and then:

dotnet ef databae update

Upvotes: 1

Related Questions