System.Data.Entity.ModelConfiguration.ModelValidationException: 'One or more validation errors were detected during model generation:
BackEnds.Producte: : EntityType 'Producte' has no key defined.
I get this error when I connect to the database, could you explain where I'm making a mistake?
Without an example of your code and the definitions of your entities, nobody will be able to help. My educated guess (based on the error message) is that the Producte entity has no key defined.
Try to decorate the property of the entity that holds the key with the Key attribute, like this:
public class Producte
{
[Key]
public Guid Id {get; set;}
public string Name {get; set;
}
Try by decorating the Identity Column property like for example "ProductID" of the entity "Producte" with an attribute "[key]".
Ex.
[key]
public int ProductID {get;set;}
refer this link
Related
I am trying to create a DbQuery of ExtendedStudent, from SQL View which was constructed form 2 diffrent tables (see code SQL below).
I have looked at the following posts:
Entity Framework Core Query Types And EF Core 2.1 Query Types
Both have used a model with a navigation propery in it, and then succeeded to fetch it from the Fluent Fluent API.
But When i tried to do so too, i got exception such as "Invalid column name 'PrefixId1'
The models I use are:
public class ExtendedStudent {
public int IdNumber {get; set;}
public string FirstName {get; set;}
public string LastName {get; set;}
public virtual Prefix Prefix {get; set;}
public int Score {get; set;}
}
public class Prefix {
[Key]
[DatabaseGenerated(DatabaseGeneratedOption.None)]
public string Id {get ;set;}
[required]
public string Name {get; set;}
}
The applicationDbContext.cs file is:
public class ApplciationDbContext : DbContext{
DbSet<Prefix> Prefixes {get; set;}
DbQuery<ExtendedStudent> ExtendedStudents {get ;set;}
...
protected override void OnModelCreating(ModelBuilder builder) {
builder.Query<ExtendedStudent>.ToView("ExtendedStudent");
builder.Query<ExtendedStudent>.HasOne<Prefix>().WithMany();
}
}
At last, I tried to fetch the data like this.
var students = applciationDbContext.ExtendedStudents.Include(v => v.Prefix).ToList();
I have created the ExtendedStudents view in SQL like this:
CREATE VIEW [Organization].[ExtendedStudent] AS
SELECT [TableA].[Student].[FirstName]
,[TableA].[Student].[LastName]
,[TableA].[Student].[PrefixId]
,[TableA].[Student].[IdNumber]
,[Evaluation].[Student].[Score]
FROM [TableA].[Student] AS [Students]
INNER JOIN [Evaluation].[Student] ON [Evaluation].[Student].StudentId = [TableA].[Student].[IdNumber]
I have tried to add a PrefixId property to ExtendedStudent, or add foreign key, But nothing have worked.
I got an error saying
"An exception of type 'System.Data.SqlClient.SqlException' occured in Microsoft.EntityFrameworkCore.dll but was not handled in user code: 'Invalid column name 'PrefixId1'.'
Here
builder.Query<ExtendedStudent>.HasOne<Prefix>().WithMany();
with .HasOne<Prefix>() you are telling EF Core to create many to one relationship without navigation property at each end.
But the navigation property ExtendedStudent.Prefix already implies relationship, hence EF Core assumes a second relationship with default FK property and column name PrefixId1 (because PrefixId is already used by the "other" relationship implied from the navigation property).
To fix that, pass the navigation property to the relationship configuration:
builder.Query<ExtendedStudent>.HasOne(e => e.Prefix).WithMany();
I am struggling with Entity framework. The thing I want to acheive is to have an entity with only Id which will define a foreign key without actual reference to the related entity. How can it be achieved?
Class.cs:
public class Class {
Guid Id {get; set} // this is my primary key
Guid ProfessorId {get; set; } // this has to be id of professor which is a foreign key
}
Professor.cs
public class Class {
Guid Id {get; set} // this is a primaty key of professor and it should constraint ProfessorId
}
I'm using fluent api. I cannot add any virtual properties to above classes (basically i cannot modify them), so how the mapping should be configured?
I understand that you cannot modify entities but you need to add at least one navigation property. It is necessary for Entity Framework in order that it understand the relationship.
In your code ProfessorId is only a scalar property.
The only other way is to execute sql command directly from your context
dbContext.Database.ExecuteSqlCommand("...");
I have a database and I want to know how to map the relationships via code. I'm not sure if I understand exactly how this works.
Suppose I have two classes:
public class Address
{
[Key]
public int AddressID {get;set;}
public String Street {get;set;}
}
public class Shipment
{
[Key]
public int ShipmentID {get;set;}
public int ShipToAddressID {get;set;}
public virtual Address ShipToAddress {get;set;}
}
I have a few questions:
Does the navigation property merely give me access to the dbset of Address?
It seems that is not the case. However, if not, how do I specify which property is the foreign key on which the relationship exists? eg: How do I tell this navigation property that it should match the Address entities based on the AddressID property ?
Again, I'm doing this all via code. So I'm mapping the properties in the OnModelCreating call in the context. So please make suggestions/provide answers with that in mind.
You are in need of the HasRequired, WithMany, and HasForeignKey configuration methods.
EntityTypeConfiguration<Shipment> config = modelBuilder.Entity<Shipment>();
config
.HasRequired(s=>s.ShipToAddress)
.WithMany()
.HasForeignKey(s=>s.ShipToAddressID)
.WillCascadeOnDelete(false);
I'm using ASP.NET MVC 3 with the Entity Framework 4 code first approach and every time I try to specify composite keys using the key attribute on my models, I get this error:
System.Data.Edm.EdmAssociationConstraint: : Number of Properties in
the Dependent and Principal Role in a relationship constraint must be
exactly identical.
I'm using the column attribute to differentiate ordering of the primary keys like so:
public class Game
{
[Key, Column(Order=0)]
public Guid GameId { get; set; }
[Key, Column(Order=1)]
public string Name { get; set; }
public string Description { get; set; }
public Game()
{
this.GameId = Guid.NewGuid();
}
}
I would like to know if there is another approach to creating composite keys, or perhaps there is a way to stop getting this error? I know that it's possible to add logic to the OnModelBuild event, but I'd rather use the key attributes on the model if possible.
Try to exclude property Name from the entity key (that I would recommend). Or, use it in all entities if you really need to make it part of the key.
My model looks like this
public Class Address
{
public int Id {get;set;}
/*Props here*/
}
public Class Person
{
public int Id {get;set;}
public String Name {get;set;}
[Required]
public Address Address{get;set;}
/*More props*/
}
Now suppose i have created a person with proper address, in future when i try to update person like this
var person= db.Persons.FirstOrDefault(p=>p.Id=1234);
person.Name="Foo";
db.SaveChanges();
It gives error saying Address is required.
So to avoid this iam including Address property too while loading Person Entity
var person= db.Persons.Include(p=>p.Address).FirstOrDefault(p=>p.Id=1234);
person.Name="Foo";
db.SaveChanges();
Is there any way i can update person Without including Address.
It's the model validation of DbContext which complains apparently. So, one solution would be to switch off this validation:
dbContext.Configuration.ValidateOnSaveEnabled = false;
The other option is to introduce a foreign key property:
public class Person
{
public int Id {get;set;}
public String Name {get;set;}
public int AddressId {get;set;}
public Address Address {get;set;}
/*More props*/
}
You can omit the [Required] attribute here because EF will detect the relationship as required by convention (due to the non-nullable FK property). This works also with enabled validation.
The behaviour is a bit confusing since EF doesn't send a change of the FK column to the database, so there is not really a constraint violation and the Update command executes fine. I guess that the validation just checks the state of the model in memory (invalid, because Address is null) and not the state the model would have in the database when SaveChanges did execute (valid, because FK is correctly set).
If you want the address to be automatically loaded by EF 4.1 you have to make the Address-porperty virtual:
public virtual Address Address{get;set;}
EF will then lazy-load the address when needed.