Here is my entity called SportTeam:
public class SportTeam : BaseEntity
{
public int Id { get; set; }
public int SportId { get; set; }
public int TeamId { get; set; }
public int TotalPlays { get; set; }
public int TotalWins { get; set; }
public int TotalDefeats { get; set; }
public int TotalDraws { get; set; }
public float WinPercentage { get; set; }
public float Score { get; set; }
// navs
public virtual Ladder Ladder { get; set; }
public int? LadderId { get; set; }
public virtual Sport Sport { get; set; }
public virtual Team Team { get; set; }
public ICollection<Match> HomeMatches { get; set; }
public ICollection<Match> RivalMatches { get; set; }
public ICollection<Match> VictorMatches { get; set; }
public virtual ICollection<TeamMember> TeamMembers { get; set; }
public virtual ICollection<Tournament> Tournaments { get; set; }
public override bool Equals(object obj)
{
SportTeam sportTeam = (SportTeam)obj;
if (sportTeam.Id == Id)
return true;
else
return false;
}
public override int GetHashCode()
{
return 2108858624 + Id.GetHashCode();
}
}
I am trying to sort the SportTeam entity by score by doing this
List<SportTeam> sportTeams =
dbContext.SportTeams
.Where(st => st.SportId == sportTeam.SportId)
.OrderByDescending(st => sportTeam.Score)
.ToList();
However when I add a watch over the sportTeams list, the list doesn't appear to be ordered by score at all. I just get an as in representation of the table.
Any hints?
You are sorting on a constant value (sportTeam.Score) Try
OrderByDescending(st => st.Score)
instead of
OrderByDescending(st => sportTeam.Score)
Related
I'm trying to delete the entities related to each other when I remove a row, but it isn't deleting the related entities. It is only deleting one entity and not the others.
My model
public class Company
{
public int CompanyId { get; set;}
public string CompanyName { get; set; }
public int CompanySize { get; set; }
public string Branche { get; set;}
public string Description {get; set;}
public Recruiter Recruiter { get; set; }
public ICollection<Post> Posts { get; set; }
}
public class Recruiter
{
public int RecruiterId { get; set; }
public string Name { get; set; }
public string Email { get; set; }
public string PhoneNumber { get; set; }
public int CompanyId { get; set; }
public Company Company { get; set; }
}
public class Post
{
public int PostId { get; set; }
public string Title { get; set; }
public string Location { get; set; }
public int Compensation { get; set; }
public string Education { get; set; }
public string StartDate { get; set; }
public string Type { get; set; }
public string Profession { get; set; }
public string Language { get; set; }
public string Description { get; set; }
public string Hours { get; set; }
public bool Checked { get; set; }
public int CompanyId { get; set; }
public Company Company { get; set; }
}
protected override void OnModelCreating(ModelBuilder modelBuilder)
{
modelBuilder.Entity<Post>()
.HasOne(post => post.Company)
.WithMany(company => company.Posts)
.IsRequired()
.OnDelete(DeleteBehavior.Cascade);
modelBuilder.SeedDatabase();
}
The call I make. So when I delete a post, I want that all the related entities are being deleted.
public Post DeclinePostRequest(int postId)
{
var request = _dbContext.Posts.Where(post => post.PostId == postId).Include(post => post.Company).ThenInclude(company => company.Recruiter).FirstOrDefault();
if(!request.Checked)
{
_dbContext.Posts.Remove(request);
_dbContext.SaveChanges();
return request;
}
return null;
}
You are deleting the many side of a 1-to-many relationship there. Everything is working as expected.
Try deleting a Company instead.
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'm running into this compile error when using ThenInclude on a entity. The error is listed below. I can't see anything wrong with the relationships between the two entities. What gives, I'm banging my head against a wall here!
'ICollection<OptionType>' does not contain a definition for 'ProductOption'
and no extension method 'ProductOption' accepting a first argument of type
'ICollection<OptionType>' could be found (are you missing a using directive or
an assembly reference?)
Here are the two entities in question and related code
public async Task<ProductEditor> Edit(Expression<Func<Product, bool>> filter)
{
var product = _repo.Find(filter)
.Include(x=>x.OptionType)
.ThenInclude(x=>x.ProductOption)
public partial class OptionType
{
public OptionType()
{
ProductOption = new HashSet<ProductOption>();
}
public int OptionTypeId { get; set; }
public int ProductId { get; set; }
public string OptionName { get; set; }
public virtual ICollection<ProductOption> ProductOption { get; set; }
public virtual Product Product { get; set; }
}
public partial class ProductOption
{
public int ProductOptionId { get; set; }
public int OptionTypeId { get; set; }
public string OptionValue { get; set; }
public decimal? Price { get; set; }
public bool IsStocked { get; set; }
public virtual OptionType OptionType { get; set; }
}
public partial class Product
{
public Product()
{
EmailLog = new HashSet<EmailLog>();
OptionType = new HashSet<OptionType>();
Order = new HashSet<Order>();
ProductDiscountCode = new HashSet<ProductDiscountCode>();
ProductPaymentMethod = new HashSet<ProductPaymentMethod>();
ProductPhoto = new HashSet<ProductPhoto>();
ProductViewCounter = new HashSet<ProductViewCounter>();
ProductWishList = new HashSet<ProductWishList>();
}
public int ProductId { get; set; }
public string Title { get; set; }
public string SubTitle { get; set; }
public string Description { get; set; }
public int CategoryId { get; set; }
public decimal RetailPrice { get; set; }
public decimal? SalePrice { get; set; }
public decimal ShippingCost { get; set; }
public int UserId { get; set; }
public bool WillShipInternational { get; set; }
public int QuantityTotal { get; set; }
public int QuantitySold { get; set; }
public bool IsActive { get; set; }
public bool IsBold { get; set; }
public bool IsHighlighted { get; set; }
public bool IsFeatured { get; set; }
public int ReturnPolicyId { get; set; }
public int ConditionId { get; set; }
public int StatusId { get; set; }
public DateTime CreateDate { get; set; }
public DateTime? PostedDate { get; set; }
public DateTime? EndDate { get; set; }
public virtual ICollection<EmailLog> EmailLog { get; set; }
public virtual ICollection<OptionType> OptionType { get; set; }
public virtual ICollection<Order> Order { get; set; }
public virtual ICollection<ProductDiscountCode> ProductDiscountCode { get; set; }
public virtual ICollection<ProductPaymentMethod> ProductPaymentMethod { get; set; }
public virtual ICollection<ProductPhoto> ProductPhoto { get; set; }
public virtual ICollection<ProductViewCounter> ProductViewCounter { get; set; }
public virtual ICollection<ProductWishList> ProductWishList { get; set; }
public virtual ProductCategory Category { get; set; }
public virtual ProductCondition Condition { get; set; }
public virtual ProductSystemReturnPolicy ReturnPolicy { get; set; }
public virtual ProductStatus Status { get; set; }
public virtual User User { get; set; }
I have 2 models:
public partial class Movie
{
public Movie()
{
TimeTables = new HashSet<TimeTable>();
}
[Key]
public int MovieId { get; set; }
public string MovieName { get; set; }
public int MovieGenre { get; set; }
public string MoviePicture { get; set; }
public string MovieDescription { get; set; }
public string MovieShortText { get; set; }
public bool? MovieIs3d { get; set; }
public bool? MovieIsImax { get; set; }
public int MovieLanguage { get; set; }
public bool? MovieSubtitled { get; set; }
public int? MovieMinimalAge { get; set; }
public bool? MovieHasDrugs { get; set; }
public bool? MovieHasViolence { get; set; }
public bool? MovieHasSex { get; set; }
public bool? MovieHasSwearing { get; set; }
public bool? MovieIsScary { get; set; }
public bool? MovieHasDiscrimination { get; set; }
public string MovieTrailer { get; set; }
public int MovieLength { get; set; }
public int? Genre_GenreId { get; set; }
public int? Language_LanguageId { get; set; }
public virtual Genre Genre { get; set; }
public virtual Language Language { get; set; }
public virtual ICollection<TimeTable> TimeTables { get; set; }
}
And:
public partial class TimeTable
{
public TimeTable()
{
Reservations = new HashSet<Reservation>();
}
public int TimeTableId { get; set; }
public int MovieId { get; set; }
public int RoomId { get; set; }
public int SeatsAvaible { get; set; }
public DateTime StartTime { get; set; }
public DateTime EndTime { get; set; }
public virtual Movie Movie { get; set; }
public virtual ICollection<Reservation> Reservations { get; set; }
public virtual Room Room { get; set; }
}
I want to show all the records from Movie which have one or more records in TimeTable and where StartDate.date == [given datetime].
With a simple query the movies are showing multiple times. I have tried a distinct() but that changes nothing.
Anybody here who have the solution?
Current query:
var times2 =
(from s in timetablerepo.TimeTables
orderby s.StartTime.TimeOfDay
where s.StartTime.Date == datetime.Date
select s).Distinct().ToList();
Why not start with movies first and filter by timetable:
var times = timetablerepo.Movies
.Where(m => m.TimeTables.Any(t => t.StartDate.Date == <yourdate>));
I'm trying to get a sum for items I have within a class. To explain you better, I'm having cart object for which I can calculate the total sum with this method:
public decimal ComputeTotalValue()
{
return itemCollection.Sum(e => e.Item.Price*e.Quantity);
}
The item object in our case is this one:
public class CartItem
{
public RestItem Item { get; set; }
public int Quantity { get; set; }
}
Now the RestItem class has these properties:
public class RestItem
{
public Guid Id { get; set; }
public string Name { get; set; }
public string Description { get; set; }
public int InStockNow { get; set; }
public int Order { get; set; }
public decimal Price { get; set; }
public bool HasImage { get; set; }
public bool HasModifiers { get; set; }
public string PLU { get; set; }
public int CategoryId { get; set; }
public byte[] ImageArray { get; set; }
public IEnumerable<ModifierOption> Modifiers { get; set; }
}
The last property, Modifiers is new property which I included today and this is the content:
public class ModifierOption
{
public string ID { get; set; }
public decimal Price { get; set; }
}
What I want to achieve is when the ComputeTotalValue is called, If there are ModifierOption fields as well, I want to calculate the sum of those fields as well and include the result in the total sum.
You can just add price of modifiers to price of your item, can't you?
public decimal ComputeTotalValue()
{
return itemCollection.Sum(e => (e.Item.Price + e.Item.Modifiers.Sum(m=>m.Price))*e.Quantity);
}
Do it like this:
public class RestItem
{
public Guid Id { get; set; }
public string Name { get; set; }
public string Description { get; set; }
public int InStockNow { get; set; }
public int Order { get; set; }
public decimal Price { get; set; }
public bool HasImage { get; set; }
public bool HasModifiers { get; set; }
public string PLU { get; set; }
public int CategoryId { get; set; }
public byte[] ImageArray { get; set; }
public IEnumerable<ModifierOption> Modifiers { get; set; }
public decimal ComputeTotalPrice() {
return (this.Modifiers?.Sum(x => x.Price) ?? 0) + Price;
}
}
public decimal ComputeTotalPrice(){
return itemCollection?.Sum(x => x.ComputeTotalPrice()) ?? 0;
}