Cannot create controller with Entity Framework - c#

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.

Related

I got a the entity type requires primary key error

When i try to connect with my database and my class i got this error
But this error appear just for my Consoles,KeyboardMouse and Headphones tables. But they have already primary keys.
and here is my context class
public class EcommContext : DbContext
{
protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
{
optionsBuilder.UseSqlServer(#"Server=.;Database=eCommerce;Trusted_Connection=true");
}
public DbSet<Product> Products { get; set; }
public DbSet<Card> Cards { get; set; }
public DbSet<Category> Categories { get; set; }
public DbSet<Consoles> Consoles { get; set; }
public DbSet<Headphone> Headphones { get; set; }
public DbSet<Order> Orders { get; set; }
public DbSet<OrderDetail> OrderDetails { get; set; }
public DbSet<Mouse> Mouses { get; set; }
public DbSet<MousePad> MousePads { get; set; }
public DbSet<Keyboard> Keyboards { get; set; }
public DbSet<KeyboardAndMouse> KeyboardMouse { get; set; }
public DbSet<Gamepad> Gamepads { get; set; }
public DbSet<Computer> Computers { get; set; }
}
And my entity classes
public class Headphone:IEntity
{
public int HeadphonesId { get; set; }
public int ProductId { get; set; }
public bool IsWireless { get; set; }
public string Type { get; set; }
public string Color { get; set; }
public bool IsGaming { get; set; }
}
public class KeyboardAndMouse:IEntity
{
public int KmId { get; set; }
public int ProductId { get; set; }
public string Color { get; set; }
}
public class Consoles:IEntity
{
public int ConsoleId { get; set; }
public int ProductId { get; set; }
public string Color { get; set; }
public int GamepadNumber { get; set; }
public int Capacity { get; set; }
}
How can I solve that. Does anyone help me ?
In your entity class you need to use [Key] annotation for primary key field. Try like below.
public class Headphone:IEntity
{
[Key]
public int HeadphonesId { get; set; }
}
public class KeyboardAndMouse:IEntity
{
[Key]
public int KmId { get; set; }
}
public class Consoles:IEntity
{
[Key]
public int ConsoleId { get; set; }
}
Please check this out for more information : https://learn.microsoft.com/en-us/ef/core/modeling/keys?tabs=data-annotations#configuring-a-primary-key
FYI - By convention, a property named Id or <type name>Id will be configured as the primary key of an entity.
So if you had HeadphoneId field in Headphone class then it will select that column as primary key by convention and no need to use [Key] annotation or Fluent API to define Primary key field.

FK column to mulitple tables POCO

I'm trying to stay in POCO, but I'm at an impasse:
Public class Alpha()
{
public int ID { get; set; }
[ForeignKey("")]
public int BetaId { get; set; }
public virtual BetaA BetaA{ get; set; }
public virtual BetaB BetaB{ get; set; }
}
Public class BetaA()
{
public int ID { get; set; }
}
Public class BetaB()
{
public int ID { get; set; }
}
How do I get Alpha.BetaId to be both ForeignKey to BetaA.ID and BetaB.ID in POCO?
If anyone else stumble around this
Solution I used
Public class Alpha()
{
public int ID { get; set; }
public int BetaId { get; set; }
[ForeignKey("BetaId")]
public virtual BetaA BetaA{ get; set; }
[ForeignKey("BetaId")]
public virtual BetaB BetaB{ get; set; }
}
Public class BetaA()
{
public int ID { get; set; }
}
Public class BetaB()
{
public int ID { get; set; }
}
have BetaA and BetaB share a primary key then reference BetaB via BetaA
You can also decorate the nav properties with the foreign key attribute and specify the int property as the FK for both, though I have not tested this scenario myself (I'm on a mobile device). Give it a shot and let me know!

Entity Framework multiple references to same table

I'm having trouble creating my database with EF code-first. I have an entity Player and an entity friedship.
Each friendship references two players. One of the players is the sender, the other one is the receiver of the friendship.
This are my entities:
Player.cs
public class Player
{
public int PlayerId { get; set; }
[Required]
public string Name { get; set; }
[Required]
public string Email { get; set; }
[InverseProperty("Receiver")]
public virtual List<Friendship> FriendshipsIncoming { get; set; }
[InverseProperty("Sender")]
public virtual List<Friendship> FriendshipsOutgoing { get; set; }
}
Friendship.cs
public class Friendship
{
public int FriendshipId { get; set; }
public int SenderId { get; set; }
public int ReceiverId { get; set; }
[ForeignKey("Sender")]
public Player Sender { get; set; }
[ForeignKey("Receiver")]
public Player Receiver { get; set; }
[Required]
public bool Confirmed { get; set; }
}
I tried implementing the relationsships the way shown in this tutorial:
http://www.entityframeworktutorial.net/code-first/inverseproperty-dataannotations-attribute-in-code-first.aspx
When trying to update the database with the "update-database" command i'm getting the following error message:
The ForeignKeyAttribute on property 'Receiver' on type 'Darta.WebApi.Models.Friendship' is not valid. The foreign key name 'Receiver' was not found on the dependent type 'Darta.WebApi.Models.Friendship'. The Name value should be a comma separated list of foreign key property names.
I also tried fixing the issue with fluent-api like shown here:
http://csharpwavenet.blogspot.sg/2013/06/multiple-foreign-keys-with-same-table.html
protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
modelBuilder.Entity<Friendship>()
.HasRequired(b => b.Sender)
.WithMany(a => a.FriendshipsOutgoing)
.HasForeignKey(b=>b.SenderId);
modelBuilder.Entity<Friendship>()
.HasRequired(b => b.Receiver)
.WithMany(a => a.FriendshipsIncoming)
.HasForeignKey(b => b.ReceiverId);
}
In this case I'm getting the following error:
Introducing FOREIGN KEY constraint 'FK_dbo.Friendships_dbo.Players_SenderId' on table 'Friendships' may cause cycles or multiple cascade paths. Specify ON DELETE NO ACTION or ON UPDATE NO ACTION, or modify other FOREIGN KEY constraints.
Could not create constraint or index. See previous errors.
You should only need either the DataAnnotations or the FluentAPI. You don't need both. If you want to use the [ForeignKey] and [InverseProperty] attributes, then get rid of the FluentAPI code.
Also, note that in the [ForeignKey] and [InverseProperty] attributes, you need to specify the name of the column, not the navigation property.
public class Player
{
public int PlayerId { get; set; }
[Required]
public string Name { get; set; }
[Required]
public string Email { get; set; }
[InverseProperty("ReceiverId")]
public virtual ICollection<Friendship> FriendshipsIncoming { get; set; }
[InverseProperty("SenderId")]
public virtual ICollection<Friendship> FriendshipsOutgoing { get; set; }
}
public class Friendship
{
public int FriendshipId { get; set; }
public int SenderId { get; set; }
public int ReceiverId { get; set; }
[ForeignKey("SenderId")]
public Player Sender { get; set; }
[ForeignKey("ReceiverId")]
public Player Receiver { get; set; }
[Required]
public bool Confirmed { get; set; }
}
I'll correct the answer. InverseProperty must be a valid entity type. So in this case Friendship.Receiver, Friendship.Sender
public class Player
{
public int PlayerId { get; set; }
[Required]
public string Name { get; set; }
[Required]
public string Email { get; set; }
[InverseProperty("Receiver")]
public virtual ICollection<Friendship> FriendshipsIncoming { get; set; }
[InverseProperty("Sender")]
public virtual ICollection<Friendship> FriendshipsOutgoing { get; set; }
}
public class Friendship
{
public int FriendshipId { get; set; }
public int SenderId { get; set; }
public int ReceiverId { get; set; }
[ForeignKey("SenderId")]
public Player Sender { get; set; }
[ForeignKey("ReceiverId")]
public Player Receiver { get; set; }
[Required]
public bool Confirmed { get; set; }
}

Entity Framework 6 - foreign key issue

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.

The navigation property 'FootballGame' was not found on the dependent type 'Bd.Domain.Entities.FootballGame'

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

Categories

Resources