Include ApplicationUser returns null - asp.net

I'm trying to include ApplicationUser, and BoardEntityFiles in BoardEntity.
When I try to include the ApplicationUser, it fetches nothing.
The structure is
BoardEntity has many BoardEntityFiles, And ApplicationUser has many BoardEntity.
using Microsoft.AspNetCore.Identity;
namespace Tutorial1.Entity;
public class ApplicationUser : IdentityUser
{
public String FirstName { get; set; }
public String LastName { get; set; }
}
using System.ComponentModel.DataAnnotations;
using System.ComponentModel.DataAnnotations.Schema;
namespace Tutorial1.Entity;
public class BoardEntity
{
public int? Id { get; set; }
public string? ApplicationUserId { get; set; }
[ForeignKey("ApplicationUserId")]
public ApplicationUser? ApplicationUser { get; set; }
[Required]
[StringLength(255, MinimumLength = 1)]
public string Title { get; set; }
[StringLength(2000, MinimumLength = 1)]
public string? Content { get; set; }
public DateTime? CreatedAt { get; set; }=DateTime.UtcNow;
public DateTime? UpdatedAt { get; set; }
public List<BoardFileEntity>? BoardFiles { get; set; }
}
using System.ComponentModel.DataAnnotations.Schema;
namespace Tutorial1.Entity;
public class BoardFileEntity
{
public int? Id { get; set; }
public string? FilePath { get; set; }
public string? EncName { get; set; }
public string? OriginalName { get; set; }
public string ? Mimetype { get; set; }
public string? Extension { get; set; }
public int? BoardEntityId { get; set; }
[ForeignKey("BoardEntityId")]
public BoardEntity BoardEntity { get; set; }
}
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.RazorPages;
using Microsoft.EntityFrameworkCore;
using Tutorial1.Data;
using Tutorial1.Entity;
namespace Tutorial1.Pages.FileUploads;
public class IndexModel : PageModel
{
private readonly ApplicationDbContext _db;
public IList<BoardEntity> BoardEntity { get; set; }
public IndexModel(ApplicationDbContext db)
{
_db = db;
}
public async Task OnGet()
{
BoardEntity = await _db.BoardEntities.Include(e=>e.BoardFiles).Include(e=>e.ApplicationUser).ToListAsync();
}
}
BoardEntity = await _db.BoardEntities.Include(e=>e.BoardFiles).Include(e=>e.ApplicationUser).ToListAsync();
When I execute this,BoardEntity.BoardFiles are fetched nicely, but BoardEntity.ApplicationUser is null.

Related

How to make request body for generic list as request parameter in wcf service

[DataContract]
public class OrderDetails
{
[DataMember(IsRequired = true)]
public string OrderReference { get; set; }
[DataMember]
public List<Product> Product { get; set; }
}
[MessageContract]
public class Product
{
[MessageBodyMember]
public string Number { get; set; }
[MessageBodyMember]
public string Code { get; set; }
[MessageBodyMember]
public string Quantity { get; set; }
}
urn:OrderDetails
urn:OrderReference?</urn:OrderReference>
urn:Product
urn:Product
urn:Number?</urn:LineNumber>
urn:Code?</urn:ProductCode>
urn:Quantity?</urn:Quantity>
</urn:Product>
</urn:Product> </urn:OrderDetails>
But I want below output urn:OrderDetails
urn:OrderReferencedf</urn:OrderReference>
urn:Product
urn:Numberf</urn:LineNumber>
urn:Codedf</urn:ProductCode>
</urn:Product>
urn:Product
urn:Numberf</urn:LineNumber>
urn:Codedf</urn:ProductCode>
</urn:Product> </urn:OrderDetails> so what I change in SerivceContract?

Expression of type 'System.Collections.Generic.List`1[API.Entities.CompanySetting]' cannot be used for parameter of type 'System.Linq.IQueryable

I am trying to find a simple way using AutoMapper to return all companies that are linked to a specific User Id in a many-to-many relationship scenario. I followed the SO Automapper many to many mapping but I get the error message "Expression of type 'System.Collections.Generic.List`1[API.Entities.CompanySetting]' cannot be used for parameter of type 'System.Linq.IQueryable" when trying to follow the logic.
My AppUser entity:
public class AppUser
{
public int Id { get; set; }
public string UserName { get; set; }
public virtual ICollection<AppUserCompanySetting> AppUserCompanySettings { get; set; } = new List<AppUserCompanySetting>();
}
My CompanySetting entity:
public class CompanySetting
{
public int Id { get; set; }
public string CompanyName { get; set; }
public string CompanyRegistrationNumber { get; set; }
public bool isActive { get; set; }
public bool isArchived { get; set; }
public virtual ICollection<AppUserCompanySetting> AppUserCompanySettings { get; set; } = new List<AppUserCompanySetting>();
}
And I have the Join table
public class AppUserCompanySetting
{
public int AppUserId { get; set; }
public virtual AppUser AppUser { get; set; }
public int CompanySettingsId { get; set; }
public virtual CompanySetting CompanySettings { get; set; }
}
I then created a CompanySettingDto
public class CompanySettingDto
{
public int Id { get; set; }
public string CompanyName { get; set; }
public string CompanyRegistrationNumber { get; set; }
public bool isActive { get; set; }
public bool isArchived { get; set; }
}
And a MemberDto:
public class MemberDto
{
public int Id { get; set; }
public string Username { get; set; }
public string PhotoUrl { get; set; }
public string KnownAs { get; set; }
public int TimeActive { get; set; }
public DateTime LastActive {get; set;}
public ICollection<PhotoDto> Photos { get; set; }
public ICollection<CompanySettingDto> CompanyInformation { get; set; }
}
I then tried Automapper to bring the relationships between the User and the Company Information I require:
public class AutoMapperProfiles : Profile
{
public AutoMapperProfiles()
{
CreateMap<AppUser, MemberDto>()
.ForMember(dest => dest.CompanyInformation, opt => opt.MapFrom(x => x.AppUserCompanySettings.Select(y => y.CompanySettings).ToList()))
CreateMap<CompanySetting, CompanySettingDto>();
}
}
I am writing an API call to get all companies that are linked to a specific UserId.
public async Task<IEnumerable<MemberDto>> GetCompaniesByUserIdAsync(int userId)
{
return await _context.Users
.Where(x => x.Id == userId)
.ProjectTo<MemberDto>(_mapper.ConfigurationProvider)
.ToListAsync();
}

Automapper missing type map configuration or unsupported mapping error

I am using Auto mapper and I am getting this error, I am getting this error within AddAsync() method. Please help me out to solve this issue.
Missing type map configuration or unsupported mapping.\r\n\r\nMapping types:\r\nDepartmentsViewModel -> Departments\r\nEmployeeAttendanceApp.ViewModels.DepartmentsViewModel -> EmployeeAttendanceApp.Models.StaffManagement.Departments
My class
public interface IMapperConfig
{
IMapper CreateMapper();
}
public class MapperConfig : IMapperConfig
{
public IMapper CreateMapper()
{
var config = new MapperConfiguration(cfg =>
{
cfg.CreateMap<RegisterStaffs, RegisterStaffViewModel>();
cfg.CreateMap<AttendanceRecorder, AttendanceRecorderViewModel>();
cfg.CreateMap<ManageLeaves, ManageLeavesViewModel>();
cfg.CreateMap<RegisterDevices, RegisterDevicesViewModel>();
cfg.CreateMap<Departments, DepartmentsViewModel>();
});
return config.CreateMapper();
}
}
public class DepartmentsViewModel
{
[Key]
public int DepartmentId { get; set; }
[DisplayName("اسم القسم/ الادارة")]
[Required(ErrorMessage = "الرجاء ادخال اسم القسم")]
public string DepartmentName { get; set; }
[DisplayName("اضافة ملاحظات القسم")]
public string Remarks { get; set; }
public bool? IsUpdated { get; set; }
public bool? IsDeleted { get; set; }
public string CreatedBy { get; set; }
public string DeletedBy { get; set; }
public string UpdatedBy { get; set; }
[DisplayName("عدد الموظفيين")]
[Required(ErrorMessage = " الرحاء إدخال عدد موظفيين القسم")]
public long? StaffNumber { get; set; }
public DateTime? CreatedDate { get; set; }
public virtual ICollection<RegisterDevicesViewModel> RegisterDevices { get; set; }
public virtual ICollection<RegisterStaffViewModel> RegisterStaffs { get; set; }
}
public partial class Departments
{
[Key]
public int DepartmentId { get; set; }
public string DepartmentName { get; set; }
public string Remarks { get; set; }
public bool? IsUpdated { get; set; }
public bool? IsDeleted { get; set; }
public string CreatedBy { get; set; }
public string DeletedBy { get; set; }
public string UpdatedBy { get; set; }
public long? StaffNumber { get; set; }
public DateTime? CreatedDate { get; set; }
public virtual ICollection<RegisterDevices> RegisterDevices { get; set; }
public virtual ICollection<RegisterStaffs> RegisterStaffs { get; set; }
}
**I am getting the error in this method**
public async Task<bool> AddAsync(DepartmentsViewModel departmentsView)
{
try
{
var department = mapper.Map<DepartmentsViewModel, Departments>(departmentsView);
await context.Departments.AddAsync(department);
await context.SaveChangesAsync();
return true;
}
catch(Exception ex)
{
logger.LogError(ex, ex.Message);
return false;
}
}
//here is startup file where I have registered the services
services.AddSingleton<IMapperConfig, MapperConfig>();
services.AddTransient<IDepartmentManager, DepartmentManager>();
I have resolved this issue by adding .ReverseMap() inside MapperConfig class
cfg.CreateMap<Departments, DepartmentsViewModel>().ReverseMap();
but still I can't understand why it didn't work previously with out it because I have seen various examples never using ReverseMap()

The navigation property was not found on the dependent type in Entity Framework migration

I fixed all the Primary Keys, gave update-database but I have the following error:
I tried to fix it with establishing the foreign keys, but I have a new error:
The ForeignKeyAttribute on property 'ID_Model' on type 'Proiect_masini_firma_taxi.Models.Masini' is not valid. The navigation property 'Modele_masini' was not found on the dependent type 'Proiect_masini_firma_taxi.Models.Masini'. The Name value should be a valid navigation property name.
Masini.cs:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.ComponentModel.DataAnnotations.Schema;
using System.ComponentModel.DataAnnotations;
namespace Proiect_masini_firma_taxi.Models
{
public enum Da_Sau_Nu
{
Da, Nu
}
public class Masini
{
[Key]
public int ID_Masina { get; set; }
public string Numar_inmatriculare { get; set; }
[ForeignKey("Modele_masini")]
public int ID_Model { get; set; }
public int An_Fabricatie { get; set; }
public int ID_proprietar { get; set; }
public Da_Sau_Nu Disponibilitate { get; set; }
public Soferi Soferi_masini { get; set; }
public Ture Ture_masini { get; set; }
public Modele_masini Masini_modele { get; set; }
internal static void ForEach(Func<object, object> p)
{
throw new NotImplementedException();
}
}
}
Modele_masini.cs:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.ComponentModel.DataAnnotations.Schema;
using System.ComponentModel.DataAnnotations;
namespace Proiect_masini_firma_taxi.Models
{
public class Modele_masini
{
[Key]
public int ID_model { get; set; }
public string Nume_model { get; set; }
public string Descriere_Model { get; set; }
public ICollection<Masini> Masini_modele { get; set; }
}
}
Soferi.cs:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.ComponentModel.DataAnnotations.Schema;
using System.ComponentModel.DataAnnotations;
namespace Proiect_masini_firma_taxi.Models
{
public enum DaSauNu
{
Da, Nu
}
public class Soferi
{
[Key]
public int ID_sofer { get; set; }
public string Nume { get; set; }
public string Prenume { get; set; }
public DateTime Data_nasterii { get; set; }
public string Serie_permis_de_conducere { get; set; }
public DateTime Data_Expirarii { get; set; }
public DaSauNu Angajat_curent { get; set; }
public ICollection<Ture> Soferi_ture { get; set; }
public ICollection<Masini> Soferi_masini { get; set; }
internal static void ForEach(Func<object, object> p)
{
throw new NotImplementedException();
}
}
}
Ture.cs:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.ComponentModel.DataAnnotations.Schema;
using System.ComponentModel.DataAnnotations;
namespace Proiect_masini_firma_taxi.Models
{
public class Ture
{
[Key]
public int ID_tura { get; set; }
[ForeignKey("Soferi")]
public int ID_sofer { get; set; }
[ForeignKey("Masini")]
public int ID_masina { get; set; }
public DateTime Moment_Start_Tura { get; set; }
public DateTime Moment_Sfarsit_Tura { get; set; }
public DateTime Moment_logare { get; set; }
public DateTime Moment_delogare { get; set; }
public Ture Ture_Sofer { get; set; }
public Masini Ture_Masini { get; set; }
}
}
Problem is that navigation property name in [ForeignKey("Modele_masini")] does not the match navigation property name in public Modele_masini Masini_modele { get; set; }.
So update your Masini mdoel class follows:
public class Masini
{
[Key]
public int ID_Masina { get; set; }
public string Numar_inmatriculare { get; set; }
[ForeignKey("Masini_modele")]
public int ID_Model { get; set; }
public int An_Fabricatie { get; set; }
public int ID_proprietar { get; set; }
public Da_Sau_Nu Disponibilitate { get; set; }
public Soferi Soferi_masini { get; set; }
public Ture Ture_masini { get; set; }
public Modele_masini Masini_modele { get; set; }
internal static void ForEach(Func<object, object> p)
{
throw new NotImplementedException();
}
}
You also have same problem in your Ture model class. So update this too as follows:
public class Ture
{
[Key]
public int ID_tura { get; set; }
[ForeignKey("Ture_Sofer")]
public int ID_sofer { get; set; }
[ForeignKey("Ture_Masini")]
public int ID_masina { get; set; }
public DateTime Moment_Start_Tura { get; set; }
public DateTime Moment_Sfarsit_Tura { get; set; }
public DateTime Moment_logare { get; set; }
public DateTime Moment_delogare { get; set; }
public Ture Ture_Sofer { get; set; }
public Masini Ture_Masini { get; set; }
}
Hope this will solve the problem!

MVC4 EF5 entity property not updating on SaveChanges()

I've been reading through lots of articles trying to learn MVC4, but I'm stumped as to why my entity is not getting updated to database.
I've been trying to modify the MVC4 VS2012 Internet template.
So, here's the Controller action:
[HttpPost, ActionName("Approve")]
[Authorize]
public ActionResult ApproveConfirmed(long id)
{
using (StudentiContext context = new StudentiContext())
{
// context.Configuration.AutoDetectChangesEnabled = false;
var studente = (from d in context.STUDENTI_STRANIERI_MASTER_REG
where d.ID_PERSONA == id
select d).Single();
STUDENTI_STRANIERI_MASTER_REG st2 = studente;
st2.ESITO = 1;
//studente.ESITO = 1;
var statos = context.Entry(studente).State;
Console.WriteLine("Before DetectChanges: {0}",statos);
//context.ChangeTracker.DetectChanges();
context.Entry(studente).State = EntityState.Modified;
context.Entry(studente).CurrentValues.SetValues(st2);
// var tracked = context.ChangeTracker.Entries();
context.Entry(studente).Property( o => o.ESITO ).IsModified = true;
TryUpdateModel(studente);
context.SaveChanges();
Console.WriteLine("After DetectChanges: {0}",statos);
return RedirectToAction("PrivateIndex");
}
}
The aim is just to update one property, ESITO and set it to 1. Currently its value is 2.
This is the model:
namespace MvcStudenti2.Models
{
using System;
using System.Collections.Generic;
public partial class STUDENTI_STRANIERI_MASTER_REG
{
public long ID_PERSONA { get; set; }
public string COGNOME { get; set; }
public string NOME { get; set; }
public string SESSO { get; set; }
public System.DateTime DATA_NASCITA { get; set; }
public long ID_STATO_NASCITA { get; set; }
public string LUOGO_NASCITA_ESTERO { get; set; }
public string CODICE_FISCALE { get; set; }
public string TITOLO_POSSEDUTO { get; set; }
public Nullable<short> DURATA_TITOLO { get; set; }
public string VOTAZIONE { get; set; }
public string UNI_PROVENIENZA { get; set; }
public long ID_STATO_UNI { get; set; }
public string CERT_LINGUISTICA { get; set; }
public string CERT_PUNTEGGIO { get; set; }
public string NOTE { get; set; }
public System.DateTime DATA_RICHIESTA { get; set; }
public short ESITO { get; set; }
public string CDS_COD { get; set; }
public string EMAIL { get; set; }
public string NUMERO_TELEFONO { get; set; }
public string INDIRIZZO { get; set; }
public string CAP_INDIRIZZO { get; set; }
public string CITTA { get; set; }
public long ID_STATO_INDIRIZZO { get; set; }
public string DESCRIZIONE_CIT_NAZ { get; set; }
public Nullable<System.DateTime> DATA_COMPLETAMENTO_ATTESO { get; set; }
public Nullable<System.DateTime> ANNO_COMPLETAMENTO { get; set; }
public Nullable<short> DURATA_CORSO_COMPLETATO { get; set; }
public decimal GPA { get; set; }
public string ALTRI_TITOLI { get; set; }
public string MADRELINGUA { get; set; }
public Nullable<short> CERT_TOEFL_PUNT { get; set; }
public string CERT_FIRSTCERT_GRADE { get; set; }
public Nullable<short> CERT_FIRSTCERT_PUNT { get; set; }
public byte[] FILE_CV { get; set; }
public byte[] FILE_CARRIERA { get; set; }
public byte[] FILE_CERT_LINGUA { get; set; }
public byte[] FILE_DOC_IDENTITA { get; set; }
public string PWD { get; set; }
public string FILE_CV_NOME { get; set; }
public string FILE_CARRIERA_NOME { get; set; }
public string FILE_CERT_LINGUA_NOME { get; set; }
public string FILE_DOC_IDENTITA_NOME { get; set; }
public string FILE_CV_TIPO { get; set; }
public string FILE_CARRIERA_TIPO { get; set; }
public string FILE_CERT_LINGUA_TIPO { get; set; }
public string FILE_DOC_IDENTITA_TIPO { get; set; }
public Nullable<short> STATO { get; set; }
public Nullable<short> VALUTATO { get; set; }
public Nullable<short> ARCHIVIATO { get; set; }
public string CDS_COD_2 { get; set; }
public Nullable<short> MAIL_INVIATA { get; set; }
public string LINK_ULTIMO_CORSO { get; set; }
public Nullable<short> ATTIVO { get; set; }
public byte[] FILE_LETTERA_ACCETTAZIONE { get; set; }
public string FILE_LETTERA_ACCETTAZIONE_NOME { get; set; }
public string FILE_LETTERA_ACCETTAZIONE_TIPO { get; set; }
}
}
Everywhere I read I find that SaveChanges() should be enough, possibly after the EntityState.Modified.
I can correctly edit the entity, if I pass the whole entity to the Action, but in this case the Approve view is a built on a Detail template, so I don't have anything to POST from it (and I'd prefer not to: I could insert a hidden field and post just that, but I'm trying to update a single filed from code, and I'm not sure if the whole entity would get updated or overwritten ).
statos goes to "modified", if I understand correctly, because I have done a query on the entity.
Another thing I don't understand is why ESITO gets update -also- in studente, but then reverts to "2" after SaveChanges().
Are property changes being detected? I've wrapped every Action in a using block, as suggested elsewhere, so not to have multiple contextx/instances around.
Could anyone please point me to what I'm doing wrong? The code above is probably over-redundant, but I've been trying everything I have found on SO.
Thanks, everyone.
The following is all that is required to change the ESITO property.
[HttpPost, ActionName("Approve")]
[Authorize]
public ActionResult ApproveConfirmed(long id)
{
using (StudentiContext context = new StudentiContext())
{
// context.Configuration.AutoDetectChangesEnabled = false;
var studente = (from d in context.STUDENTI_STRANIERI_MASTER_REG
where d.ID_PERSONA == id
select d).Single();
studente.ESITO = 1;
context.SaveChanges();
return RedirectToAction("PrivateIndex");
}
}

Resources