I have an object like this:
public class VendorHotelRoom : BaseEntity
{
public virtual ICollection<VendorHotelRoomName> VendorHotelRoomNames { get; set; }
public bool CompleteVendorHotelRoomNames { get; set; }
public Guid VendorHotelRoomDetailId { get; set; }
public virtual VendorHotelRoomDetail VendorHotelRoomDetail { get; set; }
public bool CompleteVendorHotelRoomDetail { get; set; }
public virtual ICollection<VendorHotelRoomAvailability> VendorHotelRoomAvailabilities { get; set; }
public bool CompleteVendorHotelRoomAvailabilities { get; set; }
public virtual ICollection<VendorHotelRoomFacility> VendorHotelRoomFacilities { get; set; }
public bool CompleteVendorHotelRoomFacilities { get; set; }
public virtual ICollection<VendorHotelRoomDescription> VendorHotelRoomDescriptions { get; set; }
public bool CompleteVendorHotelRoomDescriptions { get; set; }
}
I want to include objects conditionally based in boolean properties like this
var vhr = hotelContext.VendorHotelRooms.Where(c => c.Id == VendorHotelRoomId)
//if CompleteVendorHotelRoomAvailabilities true .Include(c => c.VendorHotelRoomAvailabilities )
//if condition(boolean) true .Include(c => c.VendorHotelRoomDescriptions)
//if condition(boolean) true .Include(c => c.VendorHotelRoomDetail)
//if condition(boolean) true .Include(c => c.VendorHotelRoomFacilities)
//if condition(boolean) true .Include(c => c.VendorHotelRoomNames).FirstOrDefault();
Is there any best practice way to avoid if and else?
Related
I have an error "Value cannot be null (Parameter key)" using post and put methods.
So I have to send data using a Radzen Blazor dialog
I found that my many to many relationships between (product and predefinedElements), (markets and predefinedElements) and (actuation type and predefinedelements) cause "value cannot be null" exception but I can't find what's null here...
Here is how market, predefinedElements, products and actuationType are defined in the Model
Market :
namespace BTNLib.Shared.Models
{
public partial class Market
{
public Market()
{
PredefinedElements = new HashSet<PredefinedElement>();
}
[Key]
public int MarketId { get; set; }
public string? Name { get; set; }
[InverseProperty(nameof(PredefinedElement.Markets))]
public virtual ICollection<PredefinedElement> PredefinedElements { get; set; }
}
}
PredefinedElement :
namespace BTNLib.Shared.Models
{
public partial class PredefinedElement
{
public PredefinedElement()
{
ActuationTypes = new HashSet<ActuationType>();
Markets = new HashSet<Market>();
Products = new HashSet<Product>();
}
public string? SpoolRSideStd { get; set; }
[Key]
public int PredefinedElementId { get; set; }
public string? Designation { get; set; }
public string? ConfigFileLink { get; set; }
public string? SpoolRSideRs15Rs12 { get; set; }
public string? SpoolRSideRs12Rs08 { get; set; }
public int? SectionElementPositionId { get; set; }
public int? MaxFlow { get; set; }
public int? SectionElementTypeId { get; set; }
public string? InternalPilotOilSupply { get; set; }
public int? SectionBasicFunctionId { get; set; }
public int? SectionMouvmeentNamingId { get; set; }
public int? SectionCustomerPipingId { get; set; }
public string? PortType { get; set; }
public string? ConnectorType { get; set; }
public string? Voltage { get; set; }
public string? RpnSide { get; set; }
public int? SliceTypeId { get; set; }
public string? ShortInformation { get; set; }
public string? LongInformation { get; set; }
public string? Docupedia { get; set; }
public string? SectionPicture { get; set; }
public string? SectionPictureAxo { get; set; }
public string? MasterConfigFile { get; set; }
public string? Color { get; set; }
public int? EfatemplateId { get; set; }
public int? EfaAsmTemplateId { get; set; }
public int? EfaAgzTemplateId { get; set; }
public int? EfaGezTemplateId { get; set; }
public int? TieRodThicknessSide1 { get; set; }
public int? LThreadUnderNutSide1 { get; set; }
public int? LThreadAfterNutSide1 { get; set; }
public int? NutThicknessSide1 { get; set; }
public int? InitialAnchorLenghSide1 { get; set; }
public int? LThreadUnderNutSide2 { get; set; }
public int? LThreadAfterNutSide2 { get; set; }
public int? NutThicknessSide2 { get; set; }
public int? InitialAnchorLenghSide2 { get; set; }
public int? FlangeFaceInCavityId { get; set; }
public int? FlangeFaceOut1CavityId { get; set; }
public int? FlangeFaceOut2CavityId { get; set; }
public int? RequiredFlangeFaceCavity1id { get; set; }
public int? RequiredFlangeFaceCavity2id { get; set; }
public int? RequiredFlangeFaceCavity3id { get; set; }
public int? RequiredFlangeFaceCavity4id { get; set; }
public int? RequiredFlangeFaceCavity5id { get; set; }
public int? RequiredFlangeFaceCavity6id { get; set; }
public int? RequiredFlangeFaceCavity7id { get; set; }
public int? ImageId { get; set; }
public string? Actuation { get; set; }
public virtual EfaAgzTemplate? EfaAgzTemplate { get; set; }
public virtual EfaAsmTemplate? EfaAsmTemplate { get; set; }
public virtual EfaGezTemplate? EfaGezTemplate { get; set; }
public virtual Efatemplate? Efatemplate { get; set; }
public virtual Cavity? FlangeFaceInCavity { get; set; }
public virtual Cavity? FlangeFaceOut1Cavity { get; set; }
public virtual Cavity? FlangeFaceOut2Cavity { get; set; }
public virtual Image? Image { get; set; }
public virtual Cavity? RequiredFlangeFaceCavity1 { get; set; }
public virtual Cavity? RequiredFlangeFaceCavity2 { get; set; }
public virtual Cavity? RequiredFlangeFaceCavity3 { get; set; }
public virtual Cavity? RequiredFlangeFaceCavity4 { get; set; }
public virtual Cavity? RequiredFlangeFaceCavity5 { get; set; }
public virtual Cavity? RequiredFlangeFaceCavity6 { get; set; }
public virtual Cavity? RequiredFlangeFaceCavity7 { get; set; }
public virtual SectionBasicFunction? SectionBasicFunction { get; set; }
public virtual SectionCustomerPiping? SectionCustomerPiping { get; set; }
public virtual SectionElementPosition? SectionElementPosition { get; set; }
public virtual SectionElementType? SectionElementType { get; set; }
public virtual SectionMouvementNaming? SectionMouvmeentNaming { get; set; }
public virtual SliceType? SliceType { get; set; }
[InverseProperty(nameof(ActuationType.PredefinedElements))]
public virtual ICollection<ActuationType> ActuationTypes { get; set; }
[InverseProperty(nameof(Market.PredefinedElements))]
public virtual ICollection<Market> Markets { get; set; }
[InverseProperty(nameof(Product.PredefinedElements))]
public virtual ICollection<Product> Products { get; set; }
}
}
Product :
namespace BTNLib.Shared.Models
{
public partial class Product
{
public Product()
{
PredefinedElements = new HashSet<PredefinedElement>();
}
[Key]
public int ProductsId { get; set; }
public string? Name { get; set; }
[InverseProperty(nameof(PredefinedElement.Products))]
public virtual ICollection<PredefinedElement> PredefinedElements { get; set; }
}
}
Actuation Type :
namespace BTNLib.Shared.Models
{
public partial class ActuationType
{
public ActuationType()
{
PredefinedElements = new HashSet<PredefinedElement>();
}
[Key]
public int ActuationTypeId { get; set; }
public string? Type { get; set; }
[InverseProperty(nameof(PredefinedElement.ActuationTypes))]
public virtual ICollection<PredefinedElement> PredefinedElements { get; set; }
}
}
The database context is too long to be posted here if you need it I can post it in repsonse.
When I send the data of the predefinedElement is like that :
protected async Task Submit()
{
if (Designation == null)
{
await PredefinedElementService.CreatePredefinedElement(predefinedElement);
}
else
{
await PredefinedElementService.UpdatePredefinedElement(predefinedElement);
}
}
void OnChangeMarket(IEnumerable<Market> values)
{
predefinedElement.Markets.Clear();
foreach(var Market in values)
{
predefinedElement.Markets.Add(Market);
}
}
void OnChangeProduct(IEnumerable<Product> values)
{
predefinedElement.Products.Clear();
foreach(var Product in values)
{
predefinedElement.Products.Add(Product);
}
}
void OnChangeActuationType(IEnumerable<ActuationType> values)
{
predefinedElement.ActuationTypes.Clear();
foreach(var ActuationType in values)
{
predefinedElement.ActuationTypes.Add(ActuationType);
}
}
It calls Post or Put method via a service like that :
public async Task CreatePredefinedElement(PredefinedElement predefinedElement)
{
var result = await _http.PostAsJsonAsync("api/PredefinedElements",
predefinedElement);
Console.WriteLine(result);
await SetPredefinedElement(result);
}
public async Task UpdatePredefinedElement(PredefinedElement predefinedElement)
{
var result = await
_http.PutAsJsonAsync($"api/PredefinedElements/{predefinedElement.PredefinedElementId}",
predefinedElement);
await SetPredefinedElement(result);
}
And the controller API is something like that :
The error is displayed when _context.Add or _context.Update are called
[HttpPost]
public async Task<ActionResult<List<PredefinedElement>>>
PostPredefinedElement(PredefinedElement predefinedElements)
{
try
{
_dbContext.PredefinedElements.Add(predefinedElements);
}
catch(Exception ex)
{
throw ex;
}
await _dbContext.SaveChangesAsync();
return Ok(await GetdbPredefinedElement());
}
[HttpPut("{id}")]
public async Task<ActionResult<List<PredefinedElement>>>
UpdatePredefinedElement(PredefinedElement predefinedElement)
{
if (predefinedElement == null)
{
return NotFound("Aucun element de ce type");
}
else
{
_dbContext.Update(predefinedElement);
}
await _dbContext.SaveChangesAsync();
return Ok(await GetdbPredefinedElement());
}
private async Task<List<PredefinedElement>> GetdbPredefinedElement()
{
var result = await _dbContext.PredefinedElements.Include(p => p.Products)
.Include(p => p.Markets)
.Include(p => p.ActuationTypes)
.Include(p => p.Image)
.Include(p => p.SectionElementPosition)
.Include(p => p.SectionElementType)
.Include(p => p.SectionBasicFunction)
.Include(p => p.SectionMouvmeentNaming)
.Include(p => p.SectionCustomerPiping)
.Include(p => p.SliceType)
.Include(p => p.Efatemplate)
.Include(p => p.EfaAgzTemplate)
.Include(p => p.EfaAsmTemplate)
.Include(p => p.EfaGezTemplate)
.Include(p => p.FlangeFaceInCavity)
.Include(p => p.FlangeFaceOut1Cavity)
.Include(p => p.RequiredFlangeFaceCavity1)
.Include(p => p.RequiredFlangeFaceCavity2)
.Include(p => p.RequiredFlangeFaceCavity3)
.Include(p => p.RequiredFlangeFaceCavity4)
.Include(p => p.RequiredFlangeFaceCavity5)
.Include(p => p.RequiredFlangeFaceCavity6)
.Include(p => p.RequiredFlangeFaceCavity7).ToListAsync();
return result;
}
I can't figure out what cause the exception I only know that came from many to many relationships because when I don't add entity from this relationship in the collection there are no error displayed.
I tried everything like putting [key] everywhere in the model checking my DB if there was no problem.
This project is a merge from 2 projects so there is another database context where 2 tables are linked with the first context.
EDIT : the error only happens when I try to post another predefinedelement entity or modify one resulting two entities of predefinedelement have the same entity from the table Market, Product or ActuationType.
Exemple in the Joining Table Predefinedelement_Market
PredefinedElementId : 1 MarketId : 1
and
PredefinedElementId : 2 MarketId : 1
causing the error in Entity Framework
Thanks for the help.
SOLVED:
So to prevent this error you need to had to the controller before adding the element and saving :
predefinedElements.Markets = _dbContext.Markets.Where(x => predefinedElements.Markets.Contains(x)).ToList();
predefinedElements.Products = _dbContext.Products.Where(x => predefinedElements.Products.Contains(x)).ToList();
predefinedElements.ActuationTypes = _dbContext.ActuationTypes.Where(x => predefinedElements.ActuationTypes.Contains(x)).ToList();
The problem is that when the method runs, it creates rows for the CariHareket table, no matter how many rows of the tables linked to the Kontrat.
I can't group by because EF Core doesn't support it (EF Core v3.1.9)
hareketService.GetAll(Predicate())//table name is CariHareket
.Include(s => s.Cari)
.Include(s => s.HedefHareketCariVirman)
.Include(s => s.HareketCari)
.Include(s => s.Kontrat).ThenInclude(s => s.KontratKalemler)
.Include(s => s.Kontrat).ThenInclude(s => s.KontratTarihBaglantilar)
.Include(s => s.Kontrat).ThenInclude(s => s.FaturaTalimativeTurkceFatura)
.Include(s => s.Kontrat).ThenInclude(s => s.AraciCari)
CariHareket and Kontrat model classes:
public class CariHareket
{
[Key]
public int ID { get; set; }
[ForeignKey(nameof(CariID))]
public virtual Cariler Cari { get; set; }
public int? CariID { get; set; }
[ForeignKey(nameof(KontratID))]
public virtual KontratUst Kontrat { get; set; }
public int? KontratID { get; set; }
[ForeignKey(nameof(HareketCariID))]
public virtual Cariler HareketCari { get; set; }
public int? HareketCariID { get; set; }
[ForeignKey(nameof(HedefHareketCariVirmanID))]
public virtual Cariler HedefHareketCariVirman { get; set; }
public int? HedefHareketCariVirmanID { get; set; }
...
}
public class Kontrat
{
...
[InverseProperty("Kontrat")]
public virtual BindingList<KontratMasraflarNotlar> KontratMasraflarNotlar { get; set; }
[InverseProperty("Kontrat")]
public virtual BindingList<KontratKalem> KontratKalemler { get; set; }
[InverseProperty("Kontrat")]
public virtual BindingList<KontratTarihBaglantilar> KontratTarihBaglantilar { get; set; }
[InverseProperty("Kontrat")]
public virtual BindingList<KontratKasa> KontratKasa { get; set; }
[InverseProperty("Kontrat")]
public virtual BindingList<KontratKonteyner> KontratKonteyner { get; set; }
[InverseProperty("Kontrat")]
public virtual BindingList<KontratTurkceFaturaKalem> FaturaTalimativeTurkceFatura { get; set; }
}
I have 4 classes in dbcontext,it's EventRemind.cs Event.cs House.cs Customer.cs,the code like this:
public class EventRemind
{
[Key]
public Guid Id { get; set; }
public Guid CustomerEventId { get; set; }
public DateTime RemindTime { get; set; }
public bool HasRead { get; set; }
public DateTime CreatedTime { get; set; }
[ForeignKey("CustomerEventId")]
public virtual Event CustomerEvent { get; set; }
}
public class Event
{
[Key]
public Guid Id { get; set; }
public string Title { get; set; }
public int UserId { get; set; }
public int HouseId { get; set; }
[MaxLength(800)]
public string Content { get; set; }
public DateTime CreatedTime { get; set; }
[ForeignKey("HouseId")]
public virtual House House { get; set; }
[ForeignKey("UserId")]
public virtual Customer Customer { get; set; }
public virtual ICollection<EventRemind> EventReminds { get; set; }
}
public class House
{
public int Id { get; set; }
public string Name { get; set; }
public virtual ICollection<Event> HouseEvents { get; set; }
}
public class Customer
{
public int Id { get; set; }
public string Name { get; set; }
public virtual ICollection<Event> CustomerEvents { get; set; }
}
and my dbcontext is this:
public class DataContext:DbContext
{
public DataContext(DbContextOptions options) : base(options)
{
}
public DbSet<EventRemind> EventReminds { get; set; }
public DbSet<Event> Events { get; set; }
public DbSet<House> Houses { get; set; }
public DbSet<Customer> Customers { get; set; }
protected override void OnModelCreating(ModelBuilder modelBuilder)
{
base.OnModelCreating(modelBuilder);
}
}
that means an eventRemind include an event,an event include a house and a customer,now what puzzles me is that what should I do to get the House and Customer at the same time from EventReminds,what I want is this:
var query = _dataContext.EventReminds.Include(c => c.CustomerEvent)
.ThenInclude(c => c.Customer).ThenInclude(c => c.House //this get a compile error);
why dis this happen? Can somebody help me? Thanks in advance.
I think your last operator should be just Include. Try this:
var query = _dataContext.EventReminds
.Include(c => c.CustomerEvent)
.ThenInclude(c => c.Customer)
.Include(c => c.House);
You have to write code following way.
Way1
var query =
_dataContext.EventReminds.Include(c => c.CustomerEvent).ThenInclude(c => c.Customer)
.Include(c=> c.CustomerEvent).ThenInclude(c => c.House);
Way2 (If property is not collection then it is usefull)
var query =
_dataContext.EventReminds.Include(c=> c.CustomerEvent).
.Include(c=> c.CustomerEvent.Customer)
.Include(c=> c.CustomerEvent.House);
I'm trying to create a view, which previously got an ID, which is working fine(checked in debugger, ID is correct), to invoke a method:
public ActionResult DetaljiNarudzbe(int id)
{
DetaljiNarudzbeViewModel model = new DetaljiNarudzbeViewModel();
model.Narudzba = ctx.Naruzbee.Where(x => x.Id == id).First();
model.StatusNarudzbe = ctx.StatusiNarudzbi.Where(x => x.Id == model.Narudzba.StatusNarudzbeId).FirstOrDefault();
model.Primaoc = ctx.Primaoci.Where(x => x.Id == model.Narudzba.PrimaocId).FirstOrDefault();
model.Adresa = ctx.Adrese.Where(x => x.Id == model.Narudzba.AdresaId).FirstOrDefault();
model.Grad = ctx.Gradovi.Where(x => x.Id == model.Adresa.GradId).FirstOrDefault();
model.StavkeNarudzbe = ctx.StavkeNarudzbi.Where(x => x.Narudzbe_Id == id).ToList();
model.Klijent = ctx.Klijenti.Where(x => x.Id == model.Narudzba.KlijentId).FirstOrDefault();
model.Korisnik = ctx.Korisnici.Where(x => x.Id == model.Klijent.KorisnikId).FirstOrDefault();
return View("DetaljiNarudzbe", model);
}
However, it keeps crashing at this part
model.StavkeNarudzbe = ctx.StavkeNarudzbi.Where(x => x.Narudzbe_Id == id).ToList();
It throws an exception, because for some reason, I think the context created another column called Narudzbe_Id1, which can't be null.
https://imgur.com/a/UFxXB - Image of the given exception
Further proof that it's an issue with dbcontext:
https://imgur.com/a/KEOe3
The extra column doesn't appear in the database on the SQL server's side, where I'm getting the data from.
If it helps, I'm posting the other relevant classes below:
public class StavkaNarudzbe : IEntity
{
public int Id { get; set; }
public bool IsDeleted { get; set; }
public string Naziv { get; set; }
public int Tezina { get; set; }
public double Cijena { get; set; }
public int Narudzbe_Id { get; set; }
public virtual Narudzbe Narudzbe { get; set; }
}
public class MojKontekst : DbContext
{
public MojKontekst() : base("DostavaConnString")
{
}
public DbSet<Adresa> Adrese { get; set; }
public DbSet<Grad> Gradovi { get; set; }
public DbSet<DetaljiVozila> DetaljiVozilaa { get; set; }
public DbSet<Klijent> Klijenti { get; set; }
public DbSet<Korisnik> Korisnici { get; set; }
public DbSet<Kurir> Kuriri { get; set; }
public DbSet<Kvar> Kvarovi { get; set; }
public DbSet<Obavijest> Obavijesti { get; set; }
public DbSet<Narudzbe> Naruzbee { get; set; }
public DbSet<Posiljka> Posiljke { get; set; }
public DbSet<Prelazi> Prelazii { get; set; }
public DbSet<Primaoc> Primaoci { get; set; }
public DbSet<Skladiste> Skladista { get; set; }
public DbSet<StatusNarudzbe> StatusiNarudzbi { get; set; }
public DbSet<StavkaNarudzbe> StavkeNarudzbi { get; set; }
public DbSet<Vozilo> Vozila { get; set; }
public DbSet<VrstaVozila> VrsteVozila { get; set; }
protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
base.OnModelCreating(modelBuilder);
modelBuilder.Conventions.Remove<OneToManyCascadeDeleteConvention>();
modelBuilder.Conventions.Remove<PluralizingTableNameConvention>();
}
}
public class DetaljiNarudzbeViewModel
{
public Klijent Klijent;
public Korisnik Korisnik;
public Narudzbe Narudzba;
public List<StavkaNarudzbe> StavkeNarudzbe;
public StatusNarudzbe StatusNarudzbe;
public Primaoc Primaoc;
public Adresa Adresa;
public Grad Grad;
}
public class Narudzbe : IEntity
{
public int Id { get; set; }
public bool IsDeleted { get; set; }
public string SifraNarudzbe { get; set; }
public DateTime DatumNarudzbe { get; set; }
public bool Osigurano { get; set; }
public bool BrzaDostava { get; set; }
public int BrojPaketa { get; set; }
public int KlijentId { get; set; }
public virtual Klijent Klijent { get; set; }
public int AdresaId { get; set; }
public virtual Adresa Adresa { get; set; }
public Nullable<int> PosiljkaId { get; set; }
public virtual Posiljka Posiljka { get; set; }
public int StatusNarudzbeId { get; set; }
public virtual StatusNarudzbe StatusNarudzbe{ get; set; }
public int PrimaocId { get; set; }
public virtual Primaoc Primaoc { get; set; }
public Nullable<System.DateTime> VrijemeIsporuke { get; set; }
public int CijenaNarudzbe { get; set; }
}
Exception Text: Invalid column name Narudzbe_Id1
This is Entity Framework trying to follow it's standard naming conventions for relationship columns.
See: https://msdn.microsoft.com/en-us/library/jj819164(v=vs.113).aspx for more information this.
As you are using non-standard names for your foreign key columns (i.e. Narudzbe_Id should be NarudzbeId) you'll need to let EF know how to link up your models. Either rename the properties of your classes to follow this naming convention, or use Data Annotations to explicitly tell EF about your relationships.
For example, try adding a ForeignKey attribute (found in the System.Componentmodel.Dataannotations.Schema namespace) like so:
public class StavkaNarudzbe : IEntity
{
public int Id { get; set; }
public bool IsDeleted { get; set; }
public string Naziv { get; set; }
public int Tezina { get; set; }
public double Cijena { get; set; }
public int Narudzbe_Id { get; set; }
[ForeignKey("Narudzbe_Id")]
public virtual Narudzbe Narudzbe { get; set; }
}
i have this :
Models:
{
[Table("Requests")]
public partial class RequestsModel
{
public RequestsModel()
{
this.CountView = new HashSet<RequestCountViewModels>();
}
[Key]
public int Id { get; set; }
public int? Sender { get; set; }
public int? Type { get; set; }
public string Subject { get; set; }
public string Text { get; set; }
public int? Adtype { get; set; }
public int? Status { get; set; }
[Column(TypeName = "date")]
public DateTime? SDate { get; set; }
[Column(TypeName = "date")]
public DateTime? EDate { get; set; }
public DateTime? RDate { get; set; }
public DateTime? PayDate { get; set; }
public DateTime? RespDate { get; set; }
public long? Counter { get; set; }
public string Tags { get; set; }
public string Maps { get; set; }
public int? AccBy { get; set; }
public virtual ICollection<RequestCountViewModels> CountView { get; set; }
}
[Table("Counter")]
public partial class RequestCountViewModels
{
[Key]
public long Id { get; set; }
[ForeignKey("ParentMdl")]
public int? ReqId { get; set; }
public string IP { get; set; }
public virtual RequestsModel ParentMdl { get; set; }
public DateTime? Time { get; set; }
}
}
HomeController:
public virtual ActionResult Advs(string id)
{
var model = _requestService.GetAdvertise(Convert.ToInt32(id));
return View(model);
}
RequestsService.cs
public RequestsModel GetAdvertise(int AdID)
{
return
_ctx.Requests
.AsNoTracking()
.FirstOrDefault(a => a.Id == AdID && a.Type == 1);
}
RequestsConfig.cs
HasMany(a => a.CountView)
.WithRequired(a => a.ParentMdl)
.HasForeignKey(a => a.ReqId);
these r my code, now i wanna make relationship between RequestsModel and RequestCountViewModel so that retrieve related table data from remove db
it will get request table, but need to retrieve viewcount table for every row and fill into ICOLLECTION
help me! sorry for weak english
Ok, so you need to make something like this:
public GetData()
{
var data = _ctx.Requests
.Include(p => p.CountView)
.AsNoTracking()
.Select(a => a.CountView)
.ToList();
return data;
}
i found the solution of my own problem
RequestCountViewModels should be like this :
[Table("Counter")]
public partial class RequestCountViewModels
{
public long Id { get; set; }
public string IP { get; set; }
[ForeignKey("ReqId")]
public virtual RequestsModel ParentMdl { get; set; }
public int ReqId { get; set; }
public DateTime Time { get; set; }
}
RequestService.cs :
public virtual RequestsModel GetAdvertises(int AdID)
{
return _requests
.AsNoTracking()
.Include(v => v.ViewCounts)
.Cacheable()
.FirstOrDefault(a => a.Id == AdID && a.Type == 1);
}
and in view, for loop statement should be used instead of foreach