I have the following model using EF6, where I'm trying to link a 'ContentArticleHOAsubdivision' entity to a 'SubdivisionHOA':
public partial class ContentArticleHOAsubdivision
{
public int Id { get; set; }
[ForeignKey("ContentArticleHOA")]
public long ContentArticleId { get; set; }
[ForeignKey("SubdivisionsHOA")]
public short SubdivisionId { get; set; }
public virtual ContentArticleHOA ContentArticleHOA { get; set; }
public virtual ICollection<SubdivisionHOA> SubdivisionsHOA { get; set; }
}
public partial class SubdivisionHOA
{
public short Id { get; set; }
public string Name { get; set; }
[ForeignKey("TopTierDivisionHOA")]
public byte TopTierDivisionId { get; set; }
public virtual TopTierDivisionHOA TopTierDivisionHOA { get; set; }
}
I get the error:
The foreign key component 'SubdivisionId' is not a declared property on type 'SubdivisionHOA'. Verify that it has not been explicitly excluded from the model and that it is a valid primitive property.
The 'Id' property in SubdivisionHOA I'm trying to link on needs to be named 'Id' as that's the name of the actual column in the database, so I'm not sure what I need to do?
I've tried adding [InverseProperty("Id")] before the [ForeignKey] attributes but get the same error.
Basicly the foreign key usage in EntityFramework seems like this:
public partial class ContentArticleHOAsubdivision
{
public int Id { get; set; }
...
public virtual ICollection<SubdivisionHOA> SubdivisionsHOAs { get; set; }
}
public partial class SubdivisionHOA
{
public short Id { get; set; }
...
public int ContentArticleHOAsubdivisionId { get; set; }
[ForeignKey("ContentArticleHOAsubdivisionId")]
public virtual ContentArticleHOAsubdivision ContentArticleHOAsubdivision { get; set; }
}
Just based on your code, and I have discard some unknown stuffs.
Related
I'm trying to create the table "Prodotti" with 2 foreing keys to itself but I keep having this error: "The ForeignKeyAttribute on property 'ProdottiRichiesti' on type 'BugTracking_Entity.Prodotti' is not valid. The navigation property 'Prodotti' was not found on the dependent type 'BugTracking_Entity.Prodotti'. The Name value should be a valid navigation property name."
This is my code:
[Key]
[DatabaseGenerated(DatabaseGeneratedOption.Identity)]
public int Id { get; set; }
[ForeignKey("Prodotti")]
public virtual int ProdottiRichiesti { get; set; }
[ForeignKey("Prodotti")]
public virtual int ProdottiIncompatibili { get; set; }
using System.ComponentModel.DataAnnotations.Schema;
public class Student
{
public int StudentID { get; set; }
public string StudentName { get; set; }
[ForeignKey("Standard")]
public int StandardRefId { get; set; }
public Standard Standard { get; set; }
}
public class Standard
{
public int StandardId { get; set; }
public string StandardName { get; set; }
public ICollection<Student> Students { get; set; }
}
You have to create a Prodotti class instead of Standart like that example.
This question already has an answer here:
MVC 4 Code First ForeignKeyAttribute on property ... on type ... is not valid
(1 answer)
Closed 6 years ago.
I am using entity framework code first and added a class that has a list of classes of which the classes also have to have another list of classes but when I try to do an update to the database through migrations I get this:
The ForeignKeyAttribute on property 'SubscaleStatistics' on type SubscaleScore' is not valid. The foreign key name 'SubscaleStatisticsId' was not found on the dependent type 'SubscaleScore'. The Name value should be a comma separated list of foreign key property names.
Here's what my classes look like:
public class ExamStatistics : StatisticsData
{
[Key]
[DatabaseGenerated(DatabaseGeneratedOption.Identity)]
public int Id { get; set; }
[Required]
public int TestId { get; set; }
public IList<SubscaleStatistics> Subscales { get; set; }
}
public class SubscaleStatistics
{
[Key]
[DatabaseGenerated(DatabaseGeneratedOption.Identity)]
public int SubscaleStatisticsId { get; set; }
public int TestId { get; set; }
public int SubscaleNumber { get; set; }
public int ExamStatisticsId { get; set; }
[ForeignKey("ExamStatisticsId")]
public virtual ExamStatistics ExamStatistics { get; set; }
public IList<SubscaleScore> SubscaleScores { get; set; }
}
public class SubscaleScore
{
public int TestId { get; set; }
public int Subscale { get; set; }
public double Score { get; set; }
public int SubscaleId { get; set; }
[ForeignKey("SubscaleStatisticsId")]
public virtual SubscaleStatistics SubscaleStatistics { get; set; }
}
What am I doing wrong here? Or do I need to provide more information to get what's wrong?
You need to add a foreign key property to SubscaleScore.
public int SubscaleStatisticsId { get; set; }
see here for tutorial: foreign keys
the foreignkey must be a id not the object
try something like this:
public class SubscaleScore
{
public int TestId { get; set; }
public int Subscale { get; set; }
public double Score { get; set; }
public int SubscaleId { get; set; }
[ForeignKey("SubscaleStatisticsId")]
public int SubscaleStatisticsId { get; set; }
public virtual SubscaleStatistics SubscaleStatistics { get; set; }
}
do the same for all classes with foreignkey
Getting the following error when trying to create a controller.
There was an error running the selected code generator: "Unable to retrieve metadata for "ProjectName.Models.Tecnologia". One or more validation errors were detected during model generation:
ProjectName.DataContexts.Estadistica: EntityType "Estadistica" has no key defined. Define the key for this EntityType.
Estadisticas: EntityType: EntitySet: "Estadisticas" is based on type "Estadistica" that has no key defined.
Class Tecnologia:
public class Tecnologia
{
public int ID { get; set; }
public string Nombre { get; set; }
public List<Usuario> TutoresCorrectores { get; set; }
public List<FichaProyecto> FichasProyecto { get; set; }
}
Class Estadistica
public class Estadistica
{
public int Cantidad { get; set; }
public int Porcentaje { get; set; }
}
Class DataContexts.GestionProyectodbContext
public class GestionProyectodbContext : DbContext
{
public GestionProyectodbContext() : base("DefaultConnection")
{
}
public DbSet<Carrera> Carreras { get; set; }
public DbSet<Comentario> Comentarios { get; set; }
public DbSet<EstadoFicha> Estados { get; set; }
public DbSet<FichaProyecto> FichasProyectos { get; set; }
public DbSet<Grupo> Grupos { get; set; }
public DbSet<InformeAvance> InformesAvance { get; set; }
public DbSet<InstanciaAcademica> InstanciasAcademicas { get; set; }
public DbSet<InstanciaEvaluacion> InstanciasEvaluacion { get; set; }
public DbSet<PropuestaProyecto> PropuestasProyectos { get; set; }
public DbSet<Reunion> Reuniones { get; set; }
public DbSet<Rol> ListaRoles { get; set; }
public DbSet<Tecnologia> Tecnologias { get; set; }
public DbSet<TipoAplicacion> TiposAplicaciones { get; set; }
public DbSet<TipoCliente> TiposClientes { get; set; }
public DbSet<TipoProyecto> TiposProyectos { get; set; }
public DbSet<Usuario> Usuarios { get; set; }
public DbSet<InformeTarea> InformesTareas { get; set; }
public DbSet<Documento> Documentos { get; set; }
public DbSet<InformeCorreccion> InformesCorreccion { get; set; }
}
As seen, class "Estadistica" does not have an "ID" prop, but that's because I don't want to persist it in database. Id isn't even in the "GestionProyectodbContext" class, so it shouldn't be a problem. But when trying to create a controller por class "Tecnologia", an error saying that "Estadistica" has no key is popping. I don't know why this error is coming out, and I would some help from you if you somehow know why this happens.
PD: class "Tecnologia" is not even referring to class "Estadistica".
PD2: I know how to solve this error, but it's not the way I should be doing it, because I don't want to add an "ID" property into a class that I don't want to persist in the database.
You must have an mapped entity referencing Estadistica apply the NotMapped attribute to it.
you can also use the fluent api to ignore it:
protected override void OnModelCreating(DbModelBuilder modelBuilder) {
modelBuilder.Ignore<Estadistica>();
}
EF only works when it knows the primary key of the table, By default it recognizes the primary key with name Id, but if you don't have Id column name in your table then decorate its primary key with [Key] attribute.
public class Estadistica
{
[Key]
public int Cantidad { get; set; }
public int Porcentaje { get; set; }
}
hope it helps.
I'm experiencing an unexpected error when setting up a migration after adding keys and foreign keys to my data model. I'm using VS2013 Express, with .NET framework 4.5.
When creating a data model for Entity Framework, because the relationship keys between classes aren't what is expected by convention, I'm using data annotations as outlined in the MS Data Developer Center. Here's the class code:
using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.ComponentModel.DataAnnotations.Schema;
namespace BacklogTracker.Models
{
public class WorkOrder
{
[Key]
public string woNum { get; set; }
public string woClosingStatus { get; set; }
[ForeignKey("ID")]
public virtual ICollection<Note> woNotes { get; set; }
[ForeignKey("machSN")]
public virtual Machine woMachine { get; set; }
[ForeignKey("ID")]
public virtual ICollection<Segment> woSegments { get; set; }
}
public class Machine
{
[Key]
public string machSN { get; set; }
public string machLocation { get; set; }
public string machModel { get; set; }
}
public class Segment
{
[Key]
public int ID { get; set; }
public uint segNum { get; set; }
public string segRepair { get; set; }
[ForeignKey("ID")]
public virtual ICollection<Note> segNotes { get; set; }
}
public class Note
{
[Key]
public int ID { get; set; }
public DateTime notetimestamp { get; set; }
public string notestring { get; set; }
}
}
However, when I try to perform a migration after updating the model by performing enable-migrations in the package manager console, I get the following error:
The ForeignKeyAttribute on property 'woMachine' on type
'BacklogTracker.Models.WorkOrder' is not valid. The foreign key name
'machSN' was not found on the dependent type
'BacklogTracker.Models.WorkOrder'. The Name value should be a comma
separated list of foreign key property names.
Why is my foreign key name 'machSN' not being found?
I think you have some errors in your model. Default Code First convention for ForeignKey relationship expected to have declared a foreign key property in the dependend end (WorkOrder) that match with primary key property of the principal end (Machine). It is not necessary that they have the same name, check this link. So, declare a property named machSN in your WorkOrder class:
public class WorkOrder
{
[Key]
public string woNum { get; set; }
public string woClosingStatus { get; set; }
public virtual ICollection<Note> woNotes { get; set; }
public string machSN { get; set; }
[ForeignKey("machSN")]
public virtual Machine woMachine { get; set; }
public virtual ICollection<Segment> woSegments { get; set; }
}
You can find other errors in the woNotes and woSegments navigation properties. In this side of a one-to-many relationship you don't declare a FK, is in the other side, in Note and Segment classes, for example:
public class Note
{
[Key]
public int ID { get; set; }
public DateTime notetimestamp { get; set; }
public string notestring { get; set; }
[ForeignKey("Order)]
public string woNum { get; set; }
public virtual WorkOrder Order{get;set;}
}
Delete also in the Segment class the ForeignKey attribute over segNotes navigation property for the same reasons explained before.
public class Segment
{
[Key]
public int ID { get; set; }
public uint segNum { get; set; }
public string segRepair { get; set; }
public virtual ICollection<Note> segNotes { get; set; }
}
I am creating my first asp.net mvc3 application. I'm using code first methodology. I have the following models:
public class FootballGame
{
[Key]
public Guid id_FootballGame { get; set; }
[ForeignKey("FootballGame")]
public Guid? FK_id_FootballGame { get; set; }
public virtual FootballGame PreviousFootballGame { get; set; }
[ForeignKey("FootballTeam")]
public Guid id_FootballTeam_owner { get; set; }
public virtual FootballTeam FootballTeamOwner { get; set; }
[ForeignKey("FootballTeam")]
public Guid id_FootballTeam_guest { get; set; }
public virtual FootballTeam FootballTeamGuest { get; set; }
}
public class FootballTeam
{
[Key]
public Guid id_FootballTeam { get; set; }
public string teamName { get; set; }
}
And I have the following class:
public class EFDbContext : DbContext
{
public EFDbContext() : base("name=EFDbContext") { }
public DbSet<FootballTeam> FootballTeams { get; set; }
public DbSet<FootballGame> FootballGames { get; set; }
}
Unfortunately, there is an exception:
The ForeignKeyAttribute on property 'FK_id_FootballGame' on type
'Bd.Domain.FootballGame' is not valid. The navigation
property 'FootballGame' was not found on the dependent type
'Bd.Domain.FootballGame'. The Name value should be a valid
navigation property name.
I tried to remove these lines:
[ForeignKey("FootballGame")]
public virtual FootballGame PreviousFootballGame { get; set; }
However, another exception to appear:
The ForeignKeyAttribute on property 'id_FootballTeam_owner' on type
'Bd.FootballGame' is not valid. The navigation property 'FootballTeam'
was not found on the dependent type 'Bd.FootballGame'. The Name value
should be a valid navigation property name.
I look forward to any help.
Regards, Denis.
Try this:
public class FootballGame
{
[Key]
public Guid id_FootballGame { get; set; }
public Guid? FK_id_FootballGame { get; set; }
[ForeignKey("FK_id_FootballGame")]
public virtual FootballGame PreviousFootballGame { get; set; }
public Guid id_FootballTeam_owner { get; set; }
[ForeignKey("id_FootballTeam_owner")]
public virtual FootballTeam FootballTeamOwner { get; set; }
public Guid id_FootballTeam_guest { get; set; }
[ForeignKey("id_FootballTeam_guest")]
public virtual FootballTeam FootballTeamGuest { get; set; }
}