'Entity Framework : invalid object name "TableName1"
I have a problem with Entity Framework, I think I have a problem defining the one to many mapping, but I can't seem to find it.
When I try to save my changes and add my info to the database I get the following error:
Invalid object name 'Results1'
With Results
being the name of one of my tables, for some reasons it's adding the 1 at the end.
I have a Results
table where I need to store an Id
and several other information regarding results of a test, then I have a Reasons
table where I need to store several reasons for each Result.Id
.
This is how I defined the Reasons
class:
public class Reasons
{
public int Id { get; set; }
public int ResultId { get; set; }
public string Description { get; set; }
public Results Results { get; set; }
}
Then I have the Results
class:
public class Results
{
public int Id { get; set; }
//Other properties
public ICollection<Reasons> Reasons { get; set; }
}
This is my Reasons
configuration:
configurator.
Property(p => p.Id).HasDatabaseGeneratedOption(DatabaseGeneratedOption.None);
configurator
.HasRequired<Results>(s => s.Results)
.WithMany(g => g.Reasons)
.HasForeignKey<int>(s => s.IdResults);
Solved: the only problem was that the "Reasons" and the "Results" class did not completely match the data model. Once that was repaired the problem disappeared.
Solution 1:[1]
- Rename your foreign key in
Reasons
class fromResultId
toResultsId
or explicitly use[ForeignKey("Results")]
attribute above it. From here:
EF makes a property as foreign key property when its name matches with the primary key property of a related entity
In your case it should be:
// Foreign key for Results
public int ResultsId { get; set; }
// Navigation property
public Results Results { get; set; }
- Remove your configuration instructions. There is no need to use fluent api to configure your database scheme since entity framework will do it by self. Here are examples how to configure one to many relations via code first approach
As was answered in comments it is a good practice to use singular name for a model in order to use plural form for navigational properties.
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
Solution | Source |
---|---|
Solution 1 |