First of all I get an error when I try to access the data from this column and I don't know what the reason is.
I'm working with .NET 6 and EF Core.
I have this class :
namespace Core.Entities;
public class Usuario
{
[Key]
[DatabaseGenerated(DatabaseGeneratedOption.Identity)]
public int IdTecnico { get; set; }
public string Nombre { get; set; }
public string Apellido1 { get; set; }
public string Apellido2 { get; set; }
public string NIF { get; set; }
public string EmailPersonal { get; set; }
public string EmailCorporativo { get; set; }
public string Direccion { get; set; }
public string Telefono1 { get; set; }
public string Telefono2 { get; set; }
public DateTime FechaRegistro { get; set; }
public DateTime? FechaAltaEmpresa { get; set; }
public DateTime? FechaBajaEmpresa { get; set; }
public string WebContrasena { get; set; }
public int WebRol { get; set; }
public int SeguimientNotificacion { get; set; }
public DateTime? SeguimientoFecha { get; set; }
public int? SeguimientoIntervalo { get; set; }
public decimal? EmpresaTarifa { get; set; }
public int? EmpresaCategoria { get; set; }
public string ClienteCuenta { get; set; }
public int? ClienteCategoria { get; set; }
public int? ClienteNivel { get; set; }
public string RedmineAPIKey { get; set; }
public int? RedmineIdProyecto { get; set; }
}
Table in SQL Server:
Class entity is used by this dbcontext this way:
namespace Infrastructure.Data;
public class UsuariosContext : DbContext
{
public UsuariosContext(DbContextOptions<UsuariosContext> options) : base(options)
{
}
public DbSet<Core.Entities.Usuario> Usuarios { get; set; }
}
With dependency injection, I inject it the dbcontext into this class that implements generic operations of crud:
namespace Infrastructure.Repositories;
public class UsuarioRepository : IRepository<Core.Entities.Usuario, int>
{
UsuariosContext _context;
public UsuarioRepository(UsuariosContext context)
{
_context = context;
}
public async Task<IReadOnlyList<Usuario>> GetAllAsync()
{
// I get an error because _context.set() operation is null
return await _context.Set<Usuario>().ToListAsync();
}
}
So the "presentation layer" calls this operation and I get an error:
That's because _context.set() operation is null as you see, but why is null, did I miss something?
I am doing EXACTLY the same with other db columns and it works perfectly.
DI Config:
Entity properties dont allow null, you should delete allow null values in fields in database or add ? (null operator) on model
Related
I am having issues with creating a relationship in my ASP.net Core project.
I'm Getting This Error:
Unable to determine the relationship represented by navigation property 'PortFolioDetails.StockList'
these are my Models and db context:
namespace NetworthApi12.Models
{
public class MutualFundDetails
{
public string MutualFundName { get; set; }
public int MutualFundUnits { get; set; }
}
public class PortFolioDetails
{
[Key]
public int PortFolioId { get; set; }
public string PFName { get; set; }
public List<StockDetails> StockList { get; set; }
public List<MutualFundDetails> MutualFundList { get; set; }
}
[Keyless]
public class StockDetails
{
public string StockName { get; set; }
public int StockCount { get; set; }
}
public class NetWorthAdminContext : DbContext
{
public NetWorthAdminContext(DbContextOptions<NetWorthAdminContext> options) : base(options) { }
public DbSet<MutualFundDetails> MutualFundDetails { get; set; }
public DbSet<PortFolioDetails> PortFolioDetails { get; set; }
public DbSet<StockDetails> StockDetails { get; set; }
}
}
I am using code first approach with Entity Framework 6. Three of my model classes implements inheritance and each of these model has collection which also implement inheritance. I am using TPH inheritance strategy. Everything works fine and I can insert/update with no problem at all. However, I get when I try to read data from the repo. The I get is shown below.
I have include my models, entity configuration and the line that throws this exception:
The include path expression must refer to a navigation property defined on the type. Use dotted paths for reference navigation properties and the select operator for collection navigation properties
Code:
public abstract class OrderSup
{
public OrderSup()
{
DetailOrderSups = new HashSet<DetailOrderSup>();
}
public int Id { get; set; }
public string Description { get; set; }
public decimal AmountPaid { get; set; }
public DateTime DateEntered { get; set; }
public string CusSupCode { get; set; }
public decimal NetAmount { get; set; }
public decimal TaxAmount { get; set; }
public string DespatchSatus { get; set; }
public string Reference { get; set; }
}
public abstract class DetailOrderSup
{
[Key, Column(Order = 0)]
public virtual int OrderId { get; set; }
[Key, Column(Order = 1)]
public virtual int ProductId { get; set; }
public virtual Product OrderedProducts { get; set; }
public InvoiceType InvoiceType { get; set; }
public virtual OrderSup OrderSup { get; set; }
}
public class Order : OrderSup
{
public int SalesOrderNumber { get; set; }
public InvoiceType InvoiceType { get; set; }
}
public class PurchaseOrder : OrderSup
{
public string OrderStatus { get; set; }
//public string AlocationStatus { get; set; }
public int InvoiceNumber { get; set; }
}
public class PurchaseOrderDetails : DetailOrderSup
{
public bool IsOrderPaid { get; set; }
public decimal Outstanding { get; set; }
public decimal AmountPaid { get; set; }
public bool IsDisputed { get; set; }
}
public class OrderDetails: DetailOrderSup
{
public bool IsOrderPaid { get; set; }
public decimal Outstanding { get; set; }
}
public IEnumerable<PurchaseOrder> GetPurchaseOrders()
{
// THIS IS LINE THAT THROWS EXCEPTION
return this.AppContext.Orders.OfType<PurchaseOrder>()
.Include(o => o.DetailOrderSups.OfType<PurchaseOrderDetails>());
}
class OrderSupConfiguration : EntityTypeConfiguration<OrderSup>
{
public OrderSupConfiguration()
{
HasMany(p => p.DetailOrderSups)
.WithRequired(o => o.OrderSup)
.HasForeignKey(o => o.OrderId);
}
}
Please what am I doing wrong?
Thanks in advance for your assistance
I can't seem to figure out what is going wrong here, I have configured AutoMapper as follows
services.AddAutoMapper(typeof(MetingenView), typeof(Meting));
And in the controller like this:
public MetingenController(IMapper mapper)
{
this._mapper = mapper;
}
After, I use it like this:
var entity = await this.Context.MetingenView.AsNoTracking().FirstOrDefaultAsync(g =>g.IdMeting == key);
if (entity == null)
{
return NotFound();
}
data.Patch(entity);
var meting = await this.Context.Meting.FirstOrDefaultAsync(m => m.IdMeting == key);
this._mapper.Map(entity, meting);
Then the error rolls out:
AutoMapper.AutoMapperMappingException: Missing type map configuration
or unsupported mapping.
EDIT:
Here are the Meting, and MetingenView classes:
public partial class Meting
{
public int IdMeting { get; set; }
public int IdKoeling { get; set; }
public int IdWerknemer { get; set; }
public int IdGebouw { get; set; }
public int Temperatuur { get; set; }
public DateTime AfgenomenTijd { get; set; }
public string ProductNaam { get; set; }
public string Actie { get; set; }
public DateTime? DatumOntstaan { get; set; }
public DateTime? DatumMutatie { get; set; }
public int IndVerwijderd { get; set; }
public DateTime? DatumVerwijderd { get; set; }
public virtual Gebouw IdGebouwNavigation { get; set; }
public virtual Koeling IdKoelingNavigation { get; set; }
public virtual Werknemer IdWerknemerNavigation { get; set; }
}
public partial class MetingenView
{
[Key]
public int IdKlant { get; set; }
public string Locatie { get; set; }
public string SoortKoeling { get; set; }
public int IdMeting { get; set; }
public int IdKoeling { get; set; }
public int IdWerknemer { get; set; }
public int IdGebouw { get; set; }
public int Temperatuur { get; set; }
public string Actie { get; set; }
public string ProductNaam { get; set; }
public DateTime AfgenomenTijd { get; set; }
}
I think the mapping between Meting and MetingenView is not configured in AutoMapper. If you use Asp.Net Core, you could create a profile.
public class MetingProfile : Profile
{
public MetingProfile()
{
CreateMap<MetingenView, Meting>();
}
}
This would create a default mapping that two types have the same property. If you want to config property mapping manually, Function ForMember() would be used.
For example, if you wish that the property MetingenView.IdGebouw maps Meting.IndVerwijderd, you can code this:
CreateMap<MetingenView, Meting>()
.ForMember(dest=>dest.IdGebouw, opt=>opt.MapFrom(src=>src.IndVerwijderd));
I am trying to join two tables using Entity Framework but getting System.InvalidOperationException error. The error message is:
The property 'MasterCompany' is not a navigation property of entity type 'UnitOfMeasure'. The 'Include(string)' method can only be used with a '.' separated list of navigation property names.`.
I am not sure why it is throwing it.
Other Attempts:
I also tried adding public virtual MasterCompany MasterCompany { get; set; } in UnitOfMeasure but that throws Invalid column error.
Also added [Key] in MasterCompany table for MasterCompanyId.
But both of these changes throws Invalid column name 'IsDeleted'. error.
DAL Models:
public class ApplicationDbContext : IdentityDbContext<ApplicationUser, ApplicationRole, string>
{
public DbSet<UnitOfMeasure> UnitOfMeasure { get; set; }
public DbSet<MasterCompany> MasterCompany { get; set; }
}
public class UnitOfMeasure : PasBase, IAudit
{
[Key]
public long UnitOfMeasureId { get; set; }
public string Description { get; set; }
public string ShortName { get; set; }
public string Memo { get; set; }
public string Standard { get; set; }
// [ForeignKey("MasterCompanyId")]
public Int32 MasterCompanyId { get; set; }
public bool IsActive { get; set; }
public bool IsDeleted { get; set; }
[NotMapped]
public string UploadStatus { get; set; }
[ForeignKey("MasterCompanyId")]
public virtual MasterCompany MasterCompany { get; set; }
}
public class MasterCompany:AuditableEntity
{
public int MasterCompanyId { get; set; }
public string CompanyName { get; set; }
public string TaxId { get; set; }
public string EmailAddress { get; set; }
public string Address { get; set; }
public bool? IsActive { get; set; }
}
Repository:
private ApplicationDbContext _appContext => (ApplicationDbContext)_context;
public IEnumerable<DAL.Models.UnitOfMeasure> getUnitOfMeasureData()
{
return _appContext.UnitOfMeasure
.Include("MasterCompany")
.Where(c => c.IsDeleted == false || c.IsDeleted == null)
.OrderByDescending(c => c.UnitOfMeasureId)
.ToList();
}
You need to add a MasterCompany property in the class UnitOfMeasure
public class UnitOfMeasure : PasBase, IAudit
{
[Key]
public long UnitOfMeasureId { get; set; }
public string Description { get; set; }
public string ShortName { get; set; }
public string Memo { get; set; }
public string Standard { get; set; }
public Int32 MasterCompanyId { get; set; }
[ForeignKey("MasterCompanyId")]
public MasterCompany MasterCompany { get; set; }
public bool IsActive { get; set; }
public bool IsDeleted { get; set; }
[NotMapped]
public string UploadStatus { get; set; }
}
How can I add a foreign key reference to a table in a different DbContext with Entity Framework Core?
class DonationContext : DbContext
{
public decimal Amount { get; set; }
public string DonationType { get; set; }
public string Desc { get; set; }
public int? ChackID { get; set; }
public Check Check { get; set; }
public int? DonorCreditCardID { get; set; }
public DonorCreditCard DonorCreditCard { get; set; }
public string fundraisedBy;
[NotMapped]
public string FundraisedBy
}
public class DonorContext : DbContext
{
public DbSet<DonorCreditCard> DonorCreditCards { get; set; }
public DbSet<DonorAddress> DonorAddresss { get; set; }
public DbSet<DonorPhoneNumber> DonorPhoneNumbers { get; set; }
public DbSet<DonorEmailAddress> DonorEmails { get; set; }
public DbSet<DonorFileAttachment> DonorFileAttachments { get; set; }
public DbSet<Donor> Donors { get; set; }
}
I want to reference the DonorCreditCardID column in the DonationContext to the DonorCreditCards table in the DonorContext. the migration builder wants to create a new table DonorCreditCards