Assp.net Core exeption ('Invalid column name 'ClassRoomClassId') - entity-framework

I have a problem with ASP.NET Core scaffolding. I just applied scaffolding on a simple relational model and I got this SqlException.
Microsoft.Data.SqlClient.SqlException: 'Invalid column name 'ClassRoomClassId'.'
All I have two models
ClassRoom
public class ClassRoom
{
[Key]
public int ClassId { get; set; }
public string ClassName { get; set; }
public virtual ICollection<Student> Student { get; set; }
}
Student
public class Student
{
[Key]
public int StuId { get; set; }
public string StuName { get; set; }
[ForeignKey("ClassId")]
public int? ClassId { get; set; }
public ClassRoom ClassRoom { get; set; }
}
And I get the exception when executing Students/Index.
// GET: Students
public IActionResult Index()
{
return View(_context.Student.ToList());
}
I have no column with this name 'ClassRoomClassId' !!
what would be the problem?

Try changing [ForeignKey("ClassId")] to [ForeignKey("ClassRoom")] or placing it on ClassRoom property:
public class Student
{
...
public int? ClassId { get; set; }
[ForeignKey("ClassId")]
public ClassRoom ClassRoom { get; set; }
}

Related

Entity Framework attempting to select non-existing column

I'm using Entity Framework 6.0 and have defined 2 POCO's to map to my database:
[Table("PortfolioGroups")]
public class PortfolioGroup : AuditableEntity<int>
{
[Column("Company_Id")]
public int CompanyId { get; set; }
[ForeignKey("CompanyId")]
public Company Company { get; set; }
public string Name { get; set; }
public string Description { get; set; }
public ICollection<PortfolioGroupItem> PortfolioGroupItems { get; set; }
public PortfolioGroup()
{
PortfolioGroupItems = new Collection<PortfolioGroupItem>();
}
}
And the PortfolioGroupItem:
[Table("PortfolioGroupItems")]
public class PortfolioGroupItem : AuditableEntity<int>
{
[Column("PortfolioGroup_Id")]
public int PortfolioGroupId { get; set; }
[ForeignKey("PortfolioGroupId")]
public PortfolioGroup PortfolioGroup { get; set; }
[Column("Trademark_Id")]
public int? TrademarkId { get; set; }
[ForeignKey("TrademarkId")]
public Trademark.Trademark Trademark { get; set; }
[Column("TrademarkRegistration_Id")]
public int? TrademarkRegistrationId { get; set; }
[ForeignKey("TrademarkRegistrationId")]
public TrademarkRegistration TrademarkRegistration { get; set; }
[Column("Domain_Id")]
public int? DomainId { get; set; }
[ForeignKey("DomainId")]
public Domains.Domain Domain { get; set; }
}
However - when I attempt to query the PortfolioGroups, Entity Framework for some reason attempts to query a field named "Trademark_Id" - which doesn't exist on the PortfolioGroup entity:
Context.PortfolioGroups.SingleOrDefault(i => i.Id == id && i.CompanyId == companyId);
Throws:
Invalid column name 'Trademark_Id'.
I've used this kind of setup other places in my application without any problems. I simply cannot find out why EF is trying to query a column that's not in my entity!
Any suggestions would be greatly appreciated. I'm at the end of my rope here.
Thanks guys! :)
The problem is that you've added a Navigation Property on Trademark that requires a Foreign Key on Portfolio Group:
public class Trademark
{
[Key]
public int Id { get; set; }
[MaxLength(250)]
[Required]
public string Name { get; set; }
[MaxLength(150)]
public string Filename { get; set; }
public ICollection<PortfolioGroup> PortfolioGroups { get; set; }
public Trademark()
{
PortfolioGroups = new Collection<PortfolioGroup>();
}
}
EF expects PortfolioGorup to have a Trademark_ID column to store which PortfolioGroups are associated with a Trademark.

Microsoft Entity Framework Core Parent with 2 Children [duplicate]

This question already has answers here:
EF Core returns null relations until direct access
(2 answers)
Closed 4 years ago.
So I have 3 classes:
public class OwnerDto
{
public int Id { get; set; }
public string Name { get; set; }
public string EmailAddress { get; set; }
}
public class SitterDto
{
public int Id { get; set; }
public string Name { get; set; }
public string EmailAddress { get; set; }
}
public class ReviewDto
{
public int Id { get; set; }
public int Rating { get; set; }
//[ForeignKey("OwnerId")]
public OwnerDto Owner { get; set; }
//[ForeignKey("SitterId")]
public SitterDto Sitter { get; set; }
}
But I can't figure out how to do the proper modelBuilder. Everything I tried fails :( I am learning so bear with me.
My closest attempt was this:
modelBuilder.Entity<ReviewDto>()
.HasOne(t => t.Owner).WithMany().HasForeignKey("OwnerId");
Basically Owner and Sitter are always null :( Should i keep the [ForeignKey()] stuff or should i use a different extension method?
Declare all classes with navigation properties to each other. Mark one of the tables (the dependent table) with the ForeignKey attribute on its Primary Key.
EF infers one-to-many from this:
public class OwnerDto
{
public int Id { get; set; }
public string Name { get; set; }
public string EmailAddress { get; set; }
public ICollection<ReviewDto> Reviewers{ get; set; }
public ICollection<SitterDto> Sitters{ get; set; }
}
public class SitterDto
{
public int Id { get; set; }
public string Name { get; set; }
public string EmailAddress { get; set; }
public int OwnerId{ get; set; }
[ForeignKey("OwnerId")]
public OwnerDto Owner { get; set; }
}
public class ReviewDto
{
public int Id { get; set; }
public int Rating { get; set; }
public int OwnerId{ get; set; }
[ForeignKey("OwnerId")]
public OwnerDto Owner { get; set; }
}
and EF infers one-to-one from this:
public class OwnerDto
{
...
public ReviewDto Review{ get; set; }
...
}
public class ReviewDto
{
[ForeignKey("Owner")]
public int OwnerId { get; set; }
public OwnerDto Owner{ get; set; }
...
}
You need to refer Eager Loading in this scenario, You can use the Include method to specify related data to be includethe d in query results.
var query = from review in context.Review.Include(o => o.Owner).Include(s=>s.Sitter) select review;

EFCore- Save Entity with child entity records

Here are my models:
public partial class UserDTO
{
public int UserId { get; set; }
public ICollection<Userskills> Userskills { get; set; }
}
public partial class SkillsmasterDTO
{
public sbyte SkillId { get; set; }
public string Skill { get; set; }
public ICollection<Userskills> Userskills { get; set; }
}
public partial class UserskillsDTO
{
public int UserId { get; set; }
public sbyte SkillId { get; set; }
public SkillsmasterDTO Skill { get; set; }
public UsermasterDTO User { get; set; }
}
public class UserMaster
{
public int UserId { get; set; }
public List<UserSkills> UserSkills{get;set;}
//other fields
}
public class SkillsMaster
{
public sbyte SkillId { get; set; }
public string Skill { get; set; }
}
public class UserSkills
{
public int UserId { get; set; }
public sbyte SkillId { get; set; }
public string Skill { get; set; }
}
I want to save UserMaster, and along with that I want to save UserSkills also.
I am sending data in following format:
{"FirstName": "Priya",
"LastName": "Dave",
"Email":"priya.dave#xyz.com",
"Password":"123456",
"ContactNo":"1234",
"RoleId":1,
"CreatedBy":15,
"UserTypeId":2,
"LocationId":1,
"BandId":1,
"PostId":1,
"IsActive":1,
"UserSkills":[{"SkillId":1}]
}
Code I've written for save is:
var insertedEmployee= unitOfWork.UserRepository.Add(Mapper.Map<Usermaster>(employee));
_unitOfWork.Save();
It is saving user details but UserSkills is not getting saved. How can I do that? I went through some blogs but not able to find proper solution.
Because UserSkills is persisted in a different table than UserMaster, you need to do the following for a unit of work.
Add UserMaster to context.UserMasters table
Add UserSkills to context.UserSkills table
Add UserSkills to context.UserMaster object
Then context.SaveChanges()

EF code first model not in sync with database

My EF Code First model for some reason is not in sync with the db. I'm getting this error:
{"Invalid column name 'Type_Id1'."}
The field is actually called 'Type_Id' so I'm not sure from where that 1 comes up. I have the table column called as Type_Id and also I've added a Type_Id in my type entity model.
Why might I be getting that error message, plus why I'm getting 1 at the end of the name?
Update
My Task class:
public class Task
{
public Task()
{
Language = 1;
Grades = new HashSet<Grade>();
Categories = new HashSet<Category>();
Subjects = new HashSet<Subject>();
Rooms = new Collection<Room>();
Tools = new Collection<Tool>();
}
[Key]
public int Id { get; set; }
public string Description { get; set; }
public virtual TaskType Type { get; set; }
public string Rules { get; set; }
[Required]
[StringLength(200), MinLength(1)]
public string Name { get; set; }
public int PreperationTime { get; set; }
public int InstructionTime { get; set; }
public int TaskTime { get; set; }
public int Type_Id { get; set; }
public string VideoLink { get; set; }
[Required]
public int Language { get; set; }
public int? MinimumParticipants { get; set; }
public int? MaximumParticipants { get; set; }
public int? Rating { get; set; }
[Required]
public string CreatedBy { get; set; }
public virtual ICollection<Grade> Grades { get; set; }
public virtual ICollection<Category> Categories { get; set; }
public virtual ICollection<Subject> Subjects { get; set; }
public virtual ICollection<Room> Rooms { get; set; }
public virtual ICollection<Tool> Tools { get; set; }
}
DBContext class:
public ApplicationDbContext() : base("DefaultConnection", false)
{
}
public DbSet<Task> Tasks { get; set; }
public DbSet<TaskType> TaskTypes { get; set; }
public static ApplicationDbContext Create()
{
return new ApplicationDbContext();
}
You need to add the FK attribute on your navigation property. EF is creating Type_Id1 because Type_Id already exists (although it can't tell by convention it is the FK).
[ForeignKey("Type_Id")]
public virtual TaskType Type { get; set; }
https://msdn.microsoft.com/en-us/data/jj591583.aspx#Relationships

issue in many to many relationship entity framework code first method

I have created an application in entityframework using code first method.
In application , there are two entities which have many to many relationship between them.
public class Course
{
[Key]
public int CourseId { get; set; }
public string Name { get; set; }
public ICollection<Student> Student{ get; set; }
}
public class Student
{
[Key]
public int StudentId { get; set; }
public string Name { get; set; }
public ICollection<Course> Course{ get; set; }
}
when I execute the project, it creates student table,Course table,StudentCourse table.
Now now the problem is,in StudentCourse table there are only two keys, StudentID and CourseId
I want to add additional column in that table how to do that ?
Declare a class defining that table:
public class Course
{
[Key]
public int CourseId { get; set; }
public string Name { get; set; }
public ICollection<Student> Student{ get; set; }
}
public class Student
{
[Key]
public int StudentId { get; set; }
public string Name { get; set; }
public ICollection<Course> Course{ get; set; }
}
public class StudentCourse
{
public int StudentId { get; set; }
public int CourseId { get; set; }
//More columns here
}