The column name is not valid - entity-framework

I get a common error that probably is easy to solve but I have no clue how. This is the message I get.
The column name is not valid. [ Node name (if any) = Extent1,Column name = Blog_BlogId ]
Description: An unhandled exception occurred during the execution of the current web request. Please review the stack trace for more information about the error and where it originated in the code.
Exception Details: System.Data.SqlServerCe.SqlCeException: The column name is not valid. [ Node name (if any) = Extent1,Column name = Blog_BlogId ]
This is my classes representing my entities:
public class BlogContext : DbContext
{
public BlogContext()
: base("SqlCeServices")
{
}
public DbSet<User> Users { get; set; }
public DbSet<Blog> Blogs { get; set; }
public DbSet<Post> Posts { get; set; }
public DbSet<Category> Categories { get; set; }
public DbSet<Tag> Tags { get; set; }
}
[Table("aspnet_Users")]
public class User
{
[Required]
public Guid ApplicationId { get; set; }
[Required]
public Guid UserId { get; set; }
[Required]
public string UserName { get; set; }
[Required]
public string LoweredUserName { get; set; }
public string MobileAlias { get; set; }
[Required]
public bool IsAnonymous { get; set; }
[Required]
public DateTime LastActivityDate { get; set; }
}
public class Blog
{
[Key]
public int BlogId { get; set; }
[Required]
public string Name { get; set; }
public string Url { get; set; }
public int Rating { get; set; }
public virtual ICollection<User> Editors { get; set; }
public virtual ICollection<Post> Posts { get; set; }
}
public class Post
{
[Key]
public int PostId { get; set; }
[Required, MaxLength(200)]
public string Title { get; set; }
public string Content { get; set; }
public string Abstract { get; set; }
public DateTime DateCreated { get; set; }
public DateTime DateLastEdited { get; set; }
public virtual User UserId { get; set; }
public virtual ICollection<Category> Categories { get; set; }
public virtual ICollection<Tag> Tags { get; set; }
public virtual Blog BlogId { get; set; }
}
public class Category
{
[Key]
public int CategoryId { get; set; }
[Required, MaxLength(200)]
public string Title { get; set; }
public string Description { get; set; }
public virtual ICollection<Post> Posts { get; set; }
public virtual Category ParentCategory { get; set; }
public virtual Blog BlogId { get; set; }
}
public class Tag
{
[Key]
public int TagId { get; set; }
[Required, MaxLength(200)]
public string Title { get; set; }
public virtual Blog BlogId { get; set; }
}

Consider changing your Post class so that BlogId references the FK to the associated Blog instead of the Blog object itself. Add a new property Blog to reference the actual Blog object.
public class Post
{
[Key]
public int PostId { get; set; }
[Required, MaxLength(200)]
public string Title { get; set; }
public string Content { get; set; }
public string Abstract { get; set; }
public DateTime DateCreated { get; set; }
public DateTime DateLastEdited { get; set; }
public virtual User UserId { get; set; }
public virtual ICollection<Category> Categories { get; set; }
public virtual ICollection<Tag> Tags { get; set; }
public virtual int BlogId { get; set; }
public virtual Blog Blog { get; set; }
}

You can try...ForeignKey annotation
public virtual int BlogId { get; set; }
[ForeignKey("BlogId ")]
public virtual Blog Blog { get; set; }

Detach the connection from DB, Delete any App Data related to application and rebuild and try again, It worked for me.

Related

Code first one-to-many relationship with restraints

I have the following one-to-many database structure generated by code first. Many Buttons can be added with a relation back to a single GSMUnit. BtnNo should be unique (for every GSMUnitId), and shouldn't be duplicated. Currently it is possible to duplicate. how can i prevent this?
public class GSMUnit
{
public int Id { get; set; }
[MaxLength(20)]
public string Model { get; set; }
[MaxLength(40)]
public string GsmName { get; set; }
[MaxLength(40)]
public string TelephoneNum { get; set; }
public int GSMSiteId { get; set; }
public virtual GSMSite GSMSite { get; set; }
public virtual GSMSetting GSMSettings { get; set; }
public virtual ICollection<Button> Buttons { get; set; }
}
public class Button
{
public int Id { get; set; }
[MaxLength(30)]
public string Primary { get; set; }
[MaxLength(30)]
public string Divert1 { get; set; }
[MaxLength(30)]
public string Divert2 { get; set; }
[MaxLength(30)]
public string Divert3 { get; set; }
[MaxLength(20)]
public string AptNo { get; set; }
[MaxLength(10)]
public string Code { get; set; }
[MaxLength(4)]
public string DTO { get; set; }
[MaxLength(4)]
public string Timeband { get; set; }
[MaxLength(15)]
public string BtnNo { get; set; }
[MaxLength(20)]
public string AptName { get; set; }
public int GSMUnitId { get; set; }
public virtual GSMUnit GSMUnit { get; set; }
}
You can use the Index attribute for that:
public class Button
{
public int Id { get; set; }
[MaxLength(30)]
public string Primary { get; set; }
[MaxLength(30)]
public string Divert1 { get; set; }
[MaxLength(30)]
public string Divert2 { get; set; }
[MaxLength(30)]
public string Divert3 { get; set; }
[MaxLength(20)]
public string AptNo { get; set; }
[MaxLength(10)]
public string Code { get; set; }
[MaxLength(4)]
public string DTO { get; set; }
[MaxLength(4)]
public string Timeband { get; set; }
[MaxLength(15)]
public string BtnNo { get; set; }
[MaxLength(20)]
public string AptName { get; set; }
[Index(IsUnique = true)]
public int GSMUnitId { get; set; }
public virtual GSMUnit GSMUnit { get; set; }
}
But I recommend you to take a look on Fluent API. It's easier to configure in my opinion.

c# repository ICollection navigation error

I am stuck and need help.
Checking user permission in a controller methods as below
if (User.IsInRole("CanAccessOnlyOwnDepartmentRequest"))
{
//CanAccessOnlyOwnDepartmentRequest yetkisinie sahipse
itemResult = await Repository.PaginatedListDescAsync(p => p.BranchAsset.BranchId == userBranchId &&
(p.AssigningUser.Employee.DepartmentId == branchUser.DataResult.Employee.DepartmentId ||
p.AssignedUser.Employee.DepartmentId == branchUser.DataResult.Employee.DepartmentId) &&
(p.Assignments.LastOrDefault().AssignUser.Employee.DepartmentId == branchUser.DataResult.Employee.DepartmentId),
p => p.Id, paging.PageIndex, paging.PageSize,GetNavigation:true);
}
what I am trying to do is that I want to check Request -> Assignments collections last item's assign user and assigned user Department ID whether is equal to the user who requested the result.
this is my request entity definitions of Assessments part
private ICollection<RequestAssignment> _assignments;
public virtual ICollection<RequestAssignment> Assignments
{
get => LazyLoader?.Load(this, ref _assignments);
set => _assignments = value;
}
I am using EF Core 2.1 and LazyLoading on the necessary entity property
the error I am facing:
Property 'System.Guid DepartmentId' is not defined for type 'System.Collections.Generic.IAsyncEnumerable`1[Q.Entity.Corporate.EmployeeEntity.Employee]'
Parameter name: property
EDİT :
Request Class
public Guid? BranchAssetId { get; set; }
public BranchAsset BranchAsset { get; set; }
public Guid AssigningUserId { get; set; }
public BranchUser AssigningUser { get; set; }
public Guid AssignedUserId { get; set; }
public BranchUser AssignedUser { get; set; }
public Guid StateTypeId { get; set; }
public RequestStateType StateType { get; set; }
public Ticket Ticket { get; set; }
public ICollection<RequestFeedback> Feedbacks { get; set; }
public ICollection<RequestState> States { get; set; }
public ICollection<RequestProcess> Process { get; set; }
public ICollection<RequestMessage> Messages { get; set; }
public ICollection<RequestAssignment> Assignments { get; set; }
RequestAssignment Class :
public Guid RequestId { get; set; }
public Request Request { get; set; }
public Guid AssignUserId { get; set; }
public BranchUser AssignUser{ get; set; }
public Guid AssignedUserId { get; set; }
public BranchUser AssignedUser{ get; set; }
public string Note { get; set; }
BranchUser Class:
public Guid EmployeeId { get; set; }
public Employee Employee{ get; set; }
public Guid BranchId { get; set; }
public Branch Branch { get; set; }
public Guid? ApplicationUserId { get; set; }
public ApplicationUser ApplicationUser { get; set; }
public ICollection<BranchUserRequestApproval> RequestApprovals { get; set; }
Employee Class
public Guid DepartmentId { get; set; }
public Department Department { get; set; }
public Person PersonInformation { get; set; }
public Guid BranchId { get; set; }
public Branch Branch { get; set; }

Error in creating a controller file

I am using Entity Framework. I have tried everything, searching and adding keys but Ienter image description here cannot understand what the problem is and how to resolve it.
public class Reservation
{
[Key]
public int BookingID { get; set; }
public int CustomerID { get; set; }
public int RoomID { get; set; }
public string BookingDate { get; set; }
public int Check_In { get; set; }
public int Check_Out { get; set; }
public int Adults { get; set; }
public int Children { get; set; }
public int NoOfNights { get; set; }
[ForeignKey("RoomID")]
public virtual Room Rooms { get; set; }
[ForeignKey("CustomerID")]
public virtual CustomerDetails CustomerDetail { get; set; }
public virtual ICollection<Payment> Payment { get; set; }
}
public class CustomerDetails
{
[Key]
public int CustomerID { get; set; }
public string FirstName { get; set; }
public string LastName { get; set; }
public int PostCode { get; set; }
public string State { get; set; }
public int PhoneNumber { get; set; }
public string Email { get; set; }
public string Password { get; set; }
public virtual ICollection<Reservation> Reservations { get; set; }
}
enter image description here
All tables need a primary key or you can't use Entity Framework.

Entity Framework Code first adds unwanted foreign key column

I have a many to one relationship between Categories and News.
The problem I'm having is that EF keeps adding a foreign key colum to my table which I dont want!
News class
public class News
{
public News()
{
}
[Key]
public int NewsID { get; set; }
public int PublishedByID { get; set; }
public string PublishedByFullName { get; set; }
public string PublishedByEmail { get; set; }
public DateTime DatePublished { get; set; }
public string Title { get; set; }
public string PreviewText { get; set; }
public string BlobName { get; set; }
public virtual Category Category { get; set; }
}
Categories class
public class Category
{
public Category()
{
News = new HashSet<News>();
}
[Key]
public int CategoryID { get; set; }
public string Name { get; set; }
public string CategoryTypeName { get; set; }
public virtual ICollection<News> News { get; set; }
}
Database
My question
How do I remove Category_CategoryID in News table?
I'm guessing i'm missing some code in my OnModelCreating method.
You need to add id field in News class to reference Category.
public class News
{
[Key]
public int NewsID { get; set; }
public int CategoryID { get; set; } // added
public int PublishedByID { get; set; }
public string PublishedByFullName { get; set; }
public string PublishedByEmail { get; set; }
public DateTime DatePublished { get; set; }
public string Title { get; set; }
public string PreviewText { get; set; }
public string BlobName { get; set; }
public virtual Category Category { get; set; }
}

Code First one to many relationship and category with parent category

public class Category
{
[Key]
public int CategoryId { get; set; }
public int ParentCategoryId { get; set; }
public string Name { get; set; }
public string Description { get; set; }
public int Status { get; set; }
public virtual ICollection<Category> ParentCategories { get; set; }
public virtual ICollection<ImageSet> ImageSets { get; set; }
[ForeignKey("ParentCategoryId")]
public virtual Category ParentCategory { get; set; }
}
public class ImageSet
{
[Key]
public int ImageSetId { get; set; }
public int CategoryId { get; set; }
public string Name { get; set; }
public string Description { get; set; }
public string InsertDate { get; set; }
public int Status { get; set; }
public virtual ICollection<Image> Images { get; set; }
[ForeignKey("CategoryId")]
public virtual Category Category { get; set; }
}
public class Image
{
[Key]
public int ImageId { get; set; }
public int ImageSetId { get; set; }
public string Name { get; set; }
public string Description { get; set; }
public string ImageUrl { get; set; }
public string ThumbImageUrl { get; set; }
public string InsertDate { get; set; }
public int Status { get; set; }
[ForeignKey("ImageSetId")]
public virtual ImageSet ImageSet { get; set; }
}
Context:
public DbSet<Category> Categories { get; set; }
public DbSet<Image> Images { get; set; }
public DbSet<ImageSet> ImageSets { get; set; }
error page:Introducing FOREIGN KEY constraint 'FK_dbo.ImageSets_dbo.Categories_CategoryId' on table 'ImageSets' may
cause cycles or multiple cascade paths. Specify ON DELETE NO ACTION or
ON UPDATE NO ACTION, or modify other FOREIGN KEY constraints. Could
not create constraint. See previous errors.
Whats the problem?
You need to add this:
modelBuilder.Entity<ImageSet>()
.HasRequired(is => is.Category)
.WithMany(c => c.ImageSets)
.WillCascadeOnDelete(false);
Here are good explanations of why this is happening :
https://stackoverflow.com/a/19390016/1845408
https://stackoverflow.com/a/17127512/1845408