Here im trying to get data from database using code-first but if I have a tabel Like Country
, like this:
public class Country
{
public int id { get; set; }
public string Name { get; set; }
}
contextdb
public class ContextDb: DbContext
{
public ContextDb() { }
public DbSet<Country> Country { get; set; }
...
}
when I implements as Countrys
its throwing an error:
Countries
not have dbo
Please try to make it explicit which specific table you want for this particular type
public class ContextDb : DbContext
{
protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
modelBuilder.Entity<Country>().ToTable("Country");
}
public ContextDb() { }
public DbSet<Country> Country { get; set; }
}
As an alternative, you can turn off the pluralizing convention
protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
modelBuilder.Conventions.Remove<PluralizingTableNameConvention>();
}
Another option, as mentioned in Stefan's answer, is to have an attribute over your model class (which makes the class "not-that-POCO-anymore" but technically is perfectly valid).
Usually we use plurals in the DbContext like this:
public DbSet<Country> Countries { get; set; }
EF uses an auto plural
convention, so your entity
public class Country
will translate to a datatable [dbo].[Countries]
in your database.
If you want to explicitly override the name of the table in the database you can use the following attribute.
[Table("YourNameHere")]
public class Country
{
public int id { get; set; }
public string Name { get; set; }
}
I think there is a mixup in this logic somewhere in your code.
Alternativly you can also put your table in a differnt schema
if you like:
[Table("YourNameHere", Schema = "YourSchemaNameHere")]
public class Country
{
public int id { get; set; }
public string Name { get; set; }
}
Beware with renaming the schema though, I have experienced that some migrations will break because to database index names are not always handled correctly.
note
See @Wiktor Zychla 's solution to disable the plural conventions on the whole context.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.