The navigation property was not found on the dependent type in Entity Framework migration - asp.net

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!

Related

Include ApplicationUser returns null

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.

How can i create one list from tow related table

Hi I have model with to table and a one to many relationship between
Order and status
i want to show a list with all of properties in order and the last Title in status according to Order id in order
how could i get it?
thank you
this is my code :
namespace Pur.Models
{
using System;
using System.Collections.Generic;
public partial class Order
{
public int OrdeId { get; set; }
public Nullable<int> UserID { get; set; }
public Nullable<System.DateTime> OrderDate { get; set; }
public string Description { get; set; }
public int Quantity { get; set; }
public string Unit { get; set; }
public string Priority { get; set; }
public string Department { get; set; }
public virtual ICollection<Status> Status { get; set; }
}
}
and the other:
namespace Pur.Models
{
using System;
using System.Collections.Generic;
public partial class Status
{
public int StatusId { get; set; }
public string Title { get; set; }
public int OrderID { get; set; }
public Nullable<System.DateTime> StatusDate { get; set; }
public virtual Order Order { get; set; }
}
You can create join query and then pass it to a new model
var query = your query
var Lists = db.Database.SqlQuery<OrderModel>(query);

AspNet EF6 - Entity type has no key defined

So I changed up my databases and remade them. I followed the EF6 tutorial but encountered this error when trying to create a controller with views. I did some research on the error and people said to add data annotations and I tried [Key] but I keep getting the same error. Not sure if i've forgotten anything? Thanks!
"There was an error running the selected code generator: 'Unable to retrieve metadata for 'LinkDB.Models.Identifier.' Unable to determine the principal end of an association between the type 'LinkDB.Models.Identifier' and 'LinkDB.Models.Identity'. The principal end of this association must be explicity configured using either the relationship fluent API or data annotation.'
using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
namespace LinksDB.Models
{
public class Identity
{
[Key]
public int ID { get; set; }
public int IdentifierID { get; set; }
public string contact { get; set; }
public string contactname { get; set; }
public string price { get; set; }
public virtual ICollection<Link> Links { get; set; }
public virtual Identifier Identifiers { get; set; }
public virtual Metric Metrics { get; set; }
}
}
using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
namespace LinksDB.Models
{
public class Identifier
{
[Key]
public int ID { get; set; }
public string domain { get; set; }
public virtual ICollection<Link> Links { get; set; }
public virtual Identity Identitys { get; set; }
public virtual Metric Metrics { get; set; }
}
}
using LinksDB.Models;
using System.Data.Entity;
using System.Data.Entity.ModelConfiguration.Conventions;
namespace LinksDB.DAL
{
public class LinkData : DbContext
{
public LinkData() : base("LinkData")
{
}
public DbSet<Identifier> Identifiers { get; set; }
public DbSet<Identity> Identitys { get; set; }
public DbSet<Link> Links { get; set; }
public DbSet<Metric> Metrics { get; set; }
protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
modelBuilder.Conventions.Remove<PluralizingTableNameConvention>();
}
}
}
OK, if you want a 1:1 relationship between Identity and Identifier those models should look like below where the child (Indentifier) uses the IdentityId as both it's PK and FK. You can also do this with fluent code. Start with this and then add in your Metric and Links relationships.
public class Identity
{
[Key]
public int ID { get; set; }
public string contact { get; set; }
public string contactname { get; set; }
public string price { get; set; }
public virtual Identifier Identifier { get; set; }
}
public class Identifier
{
[Key, ForeignKey("Identity")]
public int IdentityID { get; set; }
public string domain { get; set; }
public virtual Identity Identity { get; set; }
}
Example here

MVC 5 Complex View Model binding is not working

public class CreateProjeModel
{
public Proje Proje { get; set; }
public List<GeometryModel> GeometryList { get; set; }
public CreateProjeModel()
{
Proje = new Proje();
GeometryList = new List<GeometryModel>();
}
}
public class GeometryModel
{
public List<PointModel> PointList { get; set; }
public GeometryModel()
{
PointList = new List<PointModel>();
}
}
public class PointModel
{
public int X { get; set; }
public int Y { get; set; }
}
public class Proje : EntityBase
{
public int FirmaId { get; set; }
public int IlId { get; set; }
public int? IlceId { get; set; }
public int PlanTurId { get; set; }
public int EtudTurId { get; set; }
public int EtudAmacId { get; set; }
public int DilimId { get; set; }
public string Aciklama { get; set; }
public virtual Firma Firma { get; set; }
public virtual IL Il { get; set; }
public virtual ILCE Ilce { get; set; }
public virtual PlanTur PlanTur { get; set; }
public virtual EtudTur EtudTur { get; set; }
public virtual EtudAmac EtudAmac { get; set; }
public virtual Dilim Dilim { get; set; }
}
I have a complex model named CreateProjeModel. I'm using 'for' to loop collection properties and binding like below:
#Html.TextBoxFor(m => m.GeometryList[i].PointList[j].X)
Action is like below:
[HttpPost]
public async Task<ActionResult> Create(CreateProjeModel proje)
{
//ToDo
return View(proje);
}
Posted data is below:
When it comes to action, GeometryList is empty and Proje's properties are not set to post values. Where am I doing wrong?
Your problem is that your CreateProjeModel model has a property named Proje, but the parameter of your Create() method is also named proje. Your need to change the method signature to (say)
public async Task<ActionResult> Create(CreateProjeModel model)
where the parameter name is not the same as the nae of one of your properties

ASP.NET Mvc3/VS2010 error: An item with the same key has already been added

I've been trying to add a Controller in my Project, but I've been getting the error
An item with the same key has already been added.
while doing so.
I'm still a beginner at this, so I might have not noticed something, but I don't see any duplicate keys in my model.This is my database's diagram to get the general idea of what I'm trying to do:
I'm using Applications as the Model Class and ApplicationServices as the data Context Class while trying to create my ApplicationController and getting the error
An item with the same key has already been added.
Any ideas what I might be doing wrong?
The models I've created are the following:
Entity.cs:
using Microsoft.VisualBasic;
using System.Data.Entity;
using System.Data.Entity.ModelConfiguration.Conventions;
using System.ComponentModel.DataAnnotations;
namespace PostGraduate.Models
{
public class ApplicationServices : DbContext
{
public DbSet<Application.Users> Users { get; set; }
public DbSet<Application.Addresses> Addresses { get; set; }
public DbSet<Application.Applications> Applications { get; set; }
public DbSet<Application.ForeignLanguages> ForeignLanguages { get; set; }
public DbSet<Application.Gmat> Gmat { get; set; }
public DbSet<Application.PostGradStudies> PostGradStudies { get; set; }
public DbSet<Application.PreGradStudies> PreGradStudies { get; set; }
public DbSet<Application.Schoolarships> Schoolarships { get; set; }
protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
base.OnModelCreating(modelBuilder);
modelBuilder.Entity<Application.Users>().HasKey(a => a.UserId);
modelBuilder.Entity<Application.Addresses>().HasKey(a => a.Addresses_Id);
modelBuilder.Entity<Application.Applications>().HasKey(a => a.Applications_Id);
modelBuilder.Entity<Application.Applications>().Property(a => a.Applications_Id).HasDatabaseGeneratedOption(DatabaseGeneratedOption.None);
modelBuilder.Entity<Application.ForeignLanguages>().HasKey(a => a.ForeignLanguages_Id);
modelBuilder.Entity<Application.Gmat>().HasKey(a => a.Gmat_Id);
modelBuilder.Entity<Application.Gmat>().Property(a => a.Gmat_Id).HasDatabaseGeneratedOption(DatabaseGeneratedOption.None);
modelBuilder.Entity<Application.PostGradStudies>().HasKey(a => a.PostGradStudies_Id);
modelBuilder.Entity<Application.PostGradStudies>().Property(a => a.PostGradStudies_Id).HasDatabaseGeneratedOption(DatabaseGeneratedOption.None);
modelBuilder.Entity<Application.PreGradStudies>().HasKey(a => a.PreGradStudies_Id);
modelBuilder.Entity<Application.Schoolarships>().HasKey(a => a.Schoolarships_Id);
modelBuilder.Entity<Application.Schoolarships>().Property(a => a.Schoolarships_Id).HasDatabaseGeneratedOption(DatabaseGeneratedOption.None);
modelBuilder.Entity<Application.Users>().HasRequired(a => a.Applications).WithRequiredPrincipal(i => i.Users);
modelBuilder.Entity<Application.Applications>().HasMany(a => a.Addresses).WithRequired(i => i.Applications).HasForeignKey(i => i.Application_Id);
modelBuilder.Entity<Application.Applications>().HasMany(a => a.ForeignLanguages).WithRequired(i => i.Applications).HasForeignKey(i => i.Application_Id);
modelBuilder.Entity<Application.Applications>().HasOptional(a => a.Gmat).WithRequired(i => i.Applications);
modelBuilder.Entity<Application.Applications>().HasOptional(a => a.PostGradStudies).WithRequired(i => i.Applications);
modelBuilder.Entity<Application.Applications>().HasMany(a => a.PreGradStudies).WithRequired(i => i.Applications).HasForeignKey(i => i.Application_Id);
modelBuilder.Entity<Application.Applications>().HasOptional(a => a.Schoolarships).WithRequired(i => i.Applications);
}
}
}
Applications.cs:
using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.Linq;
using System.Web;
namespace PostGraduate.Models.Application
{
public class Applications
{
public Applications()
{
this.Addresses = new HashSet<Addresses>();
this.PreGradStudies = new HashSet<PreGradStudies>();
this.ForeignLanguages = new HashSet<ForeignLanguages>();
}
internal void BuildAddress(int p)
{
for (int i = 0; i < p; i++)
{
Addresses.Add(new Addresses());
}
}
internal void BuildPreGradStudies (int p)
{
for (int i = 0; i < p; i++)
{
PreGradStudies.Add(new PreGradStudies());
}
}
internal void BuildForeignLanguages(int p)
{
for (int i = 0; i < p; i++)
{
ForeignLanguages.Add(new ForeignLanguages());
}
}
public virtual Users Users { get; set; }
public virtual Gmat Gmat { get; set; }
public virtual PostGradStudies PostGradStudies { get; set; }
public virtual Schoolarships Schoolarships { get; set; }
public virtual ICollection<Addresses> Addresses { get; set; }
public virtual ICollection<PreGradStudies> PreGradStudies { get; set; }
public virtual ICollection<ForeignLanguages> ForeignLanguages { get; set; }
[ScaffoldColumn(false)]
public string Applications_Id { get; set; }
[ScaffoldColumn(false)]
public DateTime ApplicationDate { get; set; }
[Required]
public string FathersName { get; set; }
[Required]
public DateTime? Birthdate { get; set; }
[Required]
public string Birthplace { get; set; }
[Required]
public string Identification { get; set; }
[Required]
public string Country { get; set; }
[Required]
public string MobileNumber { get; set; }
[Required]
public string Profession { get; set; }
public string Activity { get; set; }
public string PostGradExtra { get; set; }
public string PostGradReapplication { get; set; }
public string ExtraInformation { get; set; }
[Required]
public string PostGradSource { get; set; }
}
}
Addresses.cs:
using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.Linq;
using System.Web;
namespace PostGraduate.Models.Application
{
public class Addresses
{
public virtual Applications Applications { get; set; }
[ScaffoldColumn(false)]
public string Addresses_Id { get; set; }
[ScaffoldColumn(false)]
public string Application_Id { get; set; }
[Required]
public string StreetAddress { get; set; }
[Required]
public string City { get; set; }
[Required]
public string PostalCode { get; set; }
[Required]
public string PhoneNumber { get; set; }
}
}
ForeignLanguages.cs:
using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.Linq;
using System.Web;
namespace PostGraduate.Models.Application
{
public class ForeignLanguages
{
public virtual Applications Applications { get; set; }
[ScaffoldColumn(false)]
public string ForeignLanguages_Id { get; set; }
[ScaffoldColumn(false)]
public string Application_Id { get; set; }
public string Language { get; set; }
public string LanguageDegree { get; set; }
public string Admission { get; set; }
public bool Delete { get; set; }
}
}
Gmat.cs:
using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.Linq;
using System.Web;
namespace PostGraduate.Models.Application
{
public class Gmat
{
public virtual Applications Applications { get; set; }
[ScaffoldColumn(false)]
public string Gmat_Id { get; set; }
public DateTime? GmatDate { get; set; }
public string GmatGrade { get; set; }
}
}
PostGradStudies.cs:
using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.Linq;
using System.Web;
namespace PostGraduate.Models.Application
{
public class PostGradStudies
{
public virtual Applications Applications { get; set; }
[ScaffoldColumn(false)]
public string PostGradStudies_Id { get; set; }
public string Aei { get; set; }
public string PostGradTitle { get; set; }
public string PostGradLength { get; set; }
public string PostGradGrade { get; set; }
public string PostGradProject { get; set; }
public string PostGradProjectGrade { get; set; }
}
}
PreGradStudies.cs:
using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.Linq;
using System.Web;
namespace PostGraduate.Models.Application
{
public class PreGradStudies
{
public virtual Applications Applications { get; set; }
[ScaffoldColumn(false)]
public string PreGradStudies_Id { get; set; }
[ScaffoldColumn(false)]
public string Application_Id { get; set; }
public string University { get; set; }
public string Department { get; set; }
public string Admission { get; set; }
public string Graduation { get; set; }
public string DegreeGrade { get; set; }
public string ThesisSubject { get; set; }
public string ThesisGrade { get; set; }
public bool Delete { get; set; }
}
}
Schoolarships.cs:
using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.Linq;
using System.Web;
namespace PostGraduate.Models.Application
{
public class Schoolarships
{
public virtual Applications Applications { get; set; }
[ScaffoldColumn(false)]
public string Schoolarships_Id { get; set; }
public string Schoolar { get; set; }
public string SchoolarshipProfession { get; set; }
public string SchoolarshipInstitution { get; set; }
}
}
Users.cs:
using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.Linq;
using System.Web;
namespace PostGraduate.Models.Application
{
public class Users
{
public virtual Applications Applications { get; set; }
public string UserId { get; set; }
public string UserName { get; set; }
}
}
Could you include your Application Controller code also?
But I suspect, that it could be because some of your entities are defined as not having autogenerated Primary Keys, that when they the objects are created, that they will all have the same key.
I would assume all the keys are set as either empty strings or NULL, so when checking for something else with a key of NULL, it would already get a match...
(sorry I don't have the best understanding of EF, but just a thought!)
One of the reason this could happen is if you have the same property twice from your view models. For example, if you have UserName on a class and you have it on another class and both are present in your view. That would create a duplicate UserName key.
I experienced this when I had two properties with the same name in one class. One a public field member and the other a get/set accessor
public class User
{
public string userName; // <---- this should be private
public string UserName
{
get { return userName; }
set { userName = value; }
}
}
Notice C# didn't complain because of case-sensitivity. I solved that by making the field variable private

Resources