Dbcontext creating columns that I never made - c#

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; }
}

Related

Lambda how to get ThenInclude at the same time in dbcontext

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);

How to delete on cascade EF core

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.

Automapper missing type map configuration

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));

C# Linq-to-Entities OrderByDescending isn't working

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)

AutoMapper Map nested ICollection

I want to map one call to another, but I got exception all the time /An exception of type 'AutoMapper.AutoMapperMappingException' occurred in AutoMapper.dll but was not handled in user code/
Here are my Source Classes:
public class Snippet
{
public Snippet()
{
this.Labels = new HashSet<Label>();
this.Commennts = new HashSet<Comment>();
}
public int Id { get; set; }
[Required]
public string Title { get; set; }
public string Description { get; set; }
[Required]
public string Code { get; set; }
public int LanguageId { get; set; }
public string UserId { get; set; }
public DateTime CreatedOn { get; set; }
public ICollection<Label> Labels { get; set; }
public ICollection<Comment> Commennts { get; set; }
public virtual Language Language { get; set; }
public virtual ApplicationUser User { get; set; }
}
public class Label
{
public int Id { get; set; }
public string Name { get; set; }
public ICollection<Snippet> Snippets { get; set; }
}
Here are my Destination classes:
public class SnippetModels
{
public class Output
{
public int Id { get; set; }
public string Title { get; set; }
public string Description { get; set; }
public DateTime CreatedOn { get; set; }
public string Code { get; set; }
public string LanguageName { get; set; }
public string UserUsername { get; set; }
public IEnumerable<LabelModels.Output> Labels { get; set; }
//TODO Comments Labels
}
}
public class LabelModels
{
public class Output
{
public int Id { get; set; }
public string Name { get; set; }
}
}
public class HomeViewModel
{
public IEnumerable<SnippetModels.Output> Snippets { get; set; }
public IEnumerable<LabelModels.Output> Labels { get; set; }
}
And finally I tied everything that pop up in my mind but no success:
Mapper.CreateMap<Snippy.Models.Label, LabelModels.Output>();
Mapper.CreateMap<IEnumerable<Snippy.Models.Label>, IEnumerable<LabelModels.Output>>();
Mapper.CreateMap<Snippy.Models.Snippet, SnippetModels.Output>()
.ForMember(dest => dest.Labels, opt => opt.MapFrom(src => src.Labels));
Mapper.CreateMap<IEnumerable<Snippy.Models.Snippet>, IEnumerable<SnippetModels.Output>>();
var newestSnippetsDatabase = this.Data.Snippets
.All()
.OrderByDescending(s => s.CreatedOn)
.Take(HomeVisibleItemsCount)
.Select(s => s)
.ToList();
var homeScreenView = new HomeViewModel
{
Snippets = Mapper.Map<IEnumerable<SnippetModels.Output>>(newestSnippetsDatabase)
};

Categories

Resources