c# repository ICollection navigation error - entity-framework

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; }

Related

Muliple Related FK in EF Core

I have segmentation class which have some price range, related office and route. I want routeCountyMap table with route and county related but I can only assign county once per segmentation.
E.g. for 200-400 segmentation has A and B office and A office has E,F,G routes; if there is X county with F route, there won't be able fore 2*00-400 segmentation*. My codes are below, how can arrange it?
public class segment
{
[Key]
public Guid segmentId { get; set; }
public string name { get; set; }
public Guid organisationId { get; set; }
}
public class office
{
[Key]
public Guid officeId { get; set; }
public string name { get; set; }
public Guid segmentId { get; set; }
public segment segment { get; set; }
}
public class route
{
[Key]
public Guid routeId { get; set; }
public string name { get; set; }
public Guid officeId { get; set; }
public office office { get; set; }
}
public class county
{
[Key]
public Guid countyId { get; set; }
public string name { get; set; }
public Guid cityId { get; set; }
}
public class routeCountyMap
{
public Guid routeCountyMapId { get; set; }
public Guid routeId { get; set; }
public Guid countyId { get; set; }
public route route { get; set; }
public county county { get; set; }
}
public class user
{
[Key]
public Guid userId { get; set; }
public string name { get; set; }
}
public class routeUserMap
{
[Key]
public Guid routeUserMapId { get; set; }
public Guid routeId { get; set; }
public Guid userId { get; set; }
public route route { get; set; }
public user user { get; set; }
}
DB diagram

Entity Framework - unwanted population of related entity

Given
public class Customer
{
public int Id { get; set; }
[Required]
[StringLength(255)]
public string Name { get; set; }
[Required]
public DateTime DateOfBirth { get; set; }
public bool IsSubscribed { get; set; }
public MembershipType MembershipType { get; set;}
public byte MembershipTypeId { get; set; }
}
why does
onDb = _context.Customers.Single(c => c.Id == customer.Id);
populate the MembershipType object??? I don't want that to happen.
Is it because I have loaded the customer with the same ID before?

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

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

The column name is not valid

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.