How to map a List in Entity Framework? - c#

I have two classes: Role and RoleViewModel.
Role class
public partial class Role
{
public Role()
{
this.Users = new HashSet<User>();
}
public int RoleId { get; set; }
public string Name { get; set; }
public string Description { get; set; }
public virtual ICollection<User> Users { get; set; }
}
RoleViewModel class
public class RoleViewModel
{
public RoleViewModel()
{
this.Users = new HashSet<UserViewModel>();
}
public int RoleId { get; set; }
public string Name { get; set; }
public string Description { get; set; }
public virtual ICollection<UserViewModel> Users { get; set; }
}
Now, I am trying to fetch a list of Role from database and map it to a list of RoleViewModel.
public static List<RoleViewModel> GetRolesService()
{
List<Role> roles =MainRepository.GetUserRoles();
var rolesVM = Mapper.Map<List<Role>, List<RoleViewModel>>(roles);
return rolesVM;
}
The problem is that rolesVM list always have Count=0, and I don't know why.
Thanks in advance!.

One solution is to ignore nested dependencies.
Mapper.CreateMap<Role, RoleViewModel>().ForMember(c=>c.Users,option=>option.Ignore());

Related

Getting data from tables with foreign keys C# entity framework

I have this classes in Code First asp.net
public class Account
{
[Key]
public int Id { get; set; }
[Column(TypeName = "nvarchar(100)")]
public string AccountTitle { get; set; }
public Classification Classification { get; set; }
}
public class Classification
{
[Key]
public int Id { get; set; }
[Column(TypeName = "nvarchar(100)")]
public string TitleClassification { get; set; }
public ICollection<Account> Accounts { get; set; }
}
public class ClassificationDto
{
public int Id { get; set; }
public string TitleClassification { get; set; }
}
In my Db Context
public DbSet<Account> Accounts { get; set; }
AccountingManager.FindAll is this
public IQueryable<T> FindAll()
{
return context.Set<T>().AsNoTracking().AsQueryable();
}
I am trying to get just the "Classification" which is just 3 but I am getting the "Account" that is associated with it too with this code:
[HttpGet]
[Route("get-classification")]
[Authorize]
public async Task<IActionResult> GetAccountClassification()
{
List<ClassificationDto> classificationList = new List<ClassificationDto>();
var accountingManager = new AccountingManager(context);
var list = accountingManager.FindAll();
classificationList = await list.Select(s => new ClassificationDto
{
Id = s.Classification.Id,
TitleClassification = s.Classification.TitleClassification,
}).ToListAsync();
return StatusCode(StatusCodes.Status200OK, classificationList);
}
This is how it is in my table
If you want to get all rows from Classification table,
add public DbSet<Classification> Classifications { get; set;} property to your DbContext class. And then implement similar to FindAll() method:
return context.Classifications.AsNoTracking().ToList()

Is there a way to Ignore specific property in asp.net core Include function from many to many relationship

I am working on Asp.net core 5 Web-api, I am using many to many relationship between User entity and Permission entity, and I need to load users permission from the database using eager loading but the data is returning a looped information including users full information but I only load the permissions. I am using a Dto to return the Json data. Here is my models and my code
Permission Model
public class Permission
{
public int Id { get; set; }
public string ClaimName { get; set; }
public IList<UserPermission> UserPermissions { get; set; }
}
UserPermission model
public class UserPermission
{
public int UserId { get; set; }
public AppUser AppUser { get; set; }
public int PermissionId { get; set; }
public Permission Permission { get; set; }
}
User model
public class AppUser
{
public int Id { get; set; }
public string FirstName { get; set; }
public string LastName { get; set; }
public ICollection<Photo> Photos { get; set; }
public DateTime Created { get; set; } = DateTime.Now;
public DateTime LastActive { get; set; }
public IList<UserPermission> UserPermissions { get; set; }
public bool Status { get; set; }
}
My user Dto
public class UserDto
{
public int Id { get; set; }
public string FirstName { get; set; }
public string LastName { get; set; }
public ICollection<Photo> Photos { get; set; }
public ICollection<UserPermission> UserPermissions { get; set; }
public string Token { get; set; }
}
My function
var sss = _context.UserPermissions
.Include(l => l.Permission)
.Where(v => v.UserId == user.Id)
.ToList();
Use [JsonIgnore] on the properties that we want to exclude.
note that we should use "using Newtonsoft.Json" name space not using "System.Text.Json.Serialization"

Reference to other entity property

I have two models in the database in a C# project looking like this:
public Company
{
{other props... }
public string Account{ get; set; }
// This is the prop I want from the Account with Account.Account == Company.Account
public int BudgetEntryType { get; set; }
}
public Account
{
public string Account{ get; set; }
public int BudgetEntryType { get; set; }
}
The value of Company.BudgetEntryType is defined in Account.BudgetEntryType, and is dependent on the value of Company.BudgetEntryType.
Is there a way of doing so? So the Company.BudgetEntryType is a reference to the Account.BudgetEntryType.
public class Company
{
public int Id { get; set; }
public string Name { get; set; }
}
public class Account
{
public int Id { get; set; }
public int BudgetEntryType { get; set; }
public int CompanyId { get; set; }
public Company Company { get; set; }
}
public class ApplicationContext : DbContext
{
public DbSet<Company> Companies { get; set; }
public DbSet<Account> Accounts { get; set; }
//other code
}
//-----using
Company company = new Company { Name = "Samsung" };
db.Companies.Add(company);
Account account = new Account { Company = company, BudgetEntryType = 2 };
db.Accounts.Add(account);
db.SaveChanges();

Eagerly loading multiple levels

What could be wrong here? I have seen others include multilevel class to Lambda expression using Select, but I'm getting this error. Can anyone help please?
public partial class Employee
{
public Employee()
{
EmployeeRole = new HashSet<EmployeeRole>();
}
public int Id { get; set; }
public string Name { get; set; }
public string UserName { get; set; }
public string Password { get; set; }
public virtual ICollection<EmployeeRole> EmployeeRole { get; set; }
}
public partial class EmployeeRole
{
public int EmployeeId { get; set; }
public int RoleId { get; set; }
public virtual Employee Employee { get; set; }
public virtual Role Role { get; set; }
}
public partial class Role
{
public Role()
{
EmployeeRole = new HashSet<EmployeeRole>();
}
public int Id { get; set; }
public string Role1 { get; set; }
public virtual ICollection<EmployeeRole> EmployeeRole { get; set; }
}
public async Task<IActionResult> Index()
{
return View(await _context.Employee.Include(a=>a.EmployeeRole.Select(r=>r.Role)).ToListAsync());
}

Link table in EntityFramework

I'm using PostGre for my RoleProvider.
That my DbContext.
public class MembershipDbContext : DbContext
{
public DbSet<User> Users { get; set; }
public DbSet<Role> Roles { get; set; }
public DbSet<RoleUser> RoleUsers { get; set; }
protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
modelBuilder.Entity<User>().ToTable("Users");
modelBuilder.Entity<Role>().ToTable("Roles");
modelBuilder.Entity<RoleUser>().ToTable("RoleUser");
}
}
And models:
public class User
{
public virtual ICollection<Role> Roles { get; set; }
public int UserId { get; set; }
public string UserName { get; set; }
public string Password { get; set; }
public string PasswordSalt { get; set; }
}
public class Role
{
public virtual ICollection<User> Users { get; set; }
public int RoleId { get; set; }
public string Name { get; set; }
}
public class RoleUser
{
[Key, ForeignKey("Role"), Column(Order = 0)]
public int RoleId { get; set; }
[Key, ForeignKey("User"), Column(Order = 1)]
public int UserId { get; set; }
public virtual Role Role { get; set; }
public virtual User User { get; set; }
}
Problem sample:
var dbContext = new MembershipDbContext();
var users = dbContext.Users.ToList();
var roles = dbContext.Roles.ToList();
//it says: "ERROR: 42P01: relation "dbo.RoleUser1" not exist"
var rolesOfFirstUser = users[0].Roles;//not working
var usersOfFirstRole = roles[0].Users;//not working
var roleUsers = dbContext.RoleUsers.ToList();//all links works perfect
What should I do to make it work?
This answer fixes it, but I have no idea where is EF creates "RoleUsers" link table. I need it.
p.s. Sorry for bad english.
You should actually make those collections (on both files) point to RoleUser, i.e. the following:
public virtual ICollection<RoleUser> RoleUsers {get;set;}

Categories

Resources