Entity Framework 6 adds "set" at the end of every entity - entity-framework

After creating a database model with Entity Framework 6 that looks like this (I am aware that .NET Core is out):
EF generates this code:
public virtual DbSet<User> User { get; set; }
public virtual DbSet<Statevalues> Statevalues { get; set; }
in the model context but also creates tables in the database that are called:
StatevaluesSet
UserSet
Why is it using Set at the end of each name?

I've tried it with EntityFramework by Microsoft version 6.2.0. with a simple DbContext with Schools and Students, and I only got a table named Schools and a table named Students.
To override standard table naming, override DbContext.OnModelCreating.
protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
// give table Schools a special name:
modelBuilder.Entity<School>()
.HasEntitySetName("MySpecialSchools");
}

Related

EF Core migration

I have a working web application (an end point) containing a few methods and connected to two tables in sql server. This application is fully implemented from scratch by myself in an ashx file and does not follow any new or old architecture, simply some methods in ashx file that are remotely called and handle requirements of client. There are shared DLLs among client and server for data handling.
For some reasons I want to upgrade client side to Dot Net core, consequently common DLL needs to be upgraded and finally the end point.
Now I'm facing the problem that EF Core only supports code first, but there are ways for scaffolding . I started with Microsoft tutorials. Then I see There are certain ways for migrating and scaffolding existing database, but I got stuck for hours in first step of using command "dotnet ef dbcontext scaffold "Data Source=..." . Then usually tutorial materials get combined with other technologies like asp.net core very fast, I need to read tons of technologies to do a simple task.
I'm worried I'm going the wrong way. there are only two tables and I can implement table structure by hand. Isn't there any sample code that I can modify it's table definitions and I can restart my project soon? If things are so hard, I will omit EF from my project and redefine the whole end point logic by text sql queries.
I can implement table structure by hand.
Great. Simply create a DbContext subtype that has a DbSet for each of your entities. The only thing scaffolding does is save you time.
Here's a complete example for SQL Server:
public class Customer
{
public int Id { get; set; }
public string Name { get; set; }
public ICollection<Order> Orders { get; } = new HashSet<Order>();
}
public class Order
{
public int CustomerId { get; set; }
public int Id { get; set; }
public Customer Customer { get; set; }
}
public class Db : DbContext
{
string connectionString = "Server=localhost; database=efcore5test; integrated security = true;TrustServerCertificate=true;";
public DbSet<Customer> Customers { get; set; }
public DbSet<Order> Orders{ get; set; }
public Db(string connectionString) : base()
{
this.connectionString = connectionString;
}
public Db() : base()
{
this.Database.SetCommandTimeout(180);
}
protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
{
var constr = this.connectionString;
optionsBuilder.LogTo(Console.WriteLine);
optionsBuilder.UseSqlServer(constr, o => o.UseRelationalNulls().CommandTimeout(180).UseNetTopologySuite());
base.OnConfiguring(optionsBuilder);
}
protected override void OnModelCreating(ModelBuilder modelBuilder)
{
modelBuilder.Entity<Order>().HasKey(o => new { o.CustomerId, o.Id });
base.OnModelCreating(modelBuilder);
}
}

Model-first Entity Framework - how to have multiple schemas

I googled/searched for an answer here in SO, but didn't find anything, specially specific for model-first approach.
I am just starting with creation of a new model for my new database and want to organize the entities for tables that logically belong to different scopes by having multiple schemas. I am using .NET-4.5
thanks in advance.
imagine that you have these two classes (Models):
public class Order
{
}
public class Book
{
}
now in entity framework code first, you can implement the table in schema like this:
public class ContextClass : DbContext
{
protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
modelBuilder.Entity<Order>().ToTable("Order", schemaName: "Orders");
modelBuilder.Entity<Book>().ToTable("Book", schemaName: "Books");
}
public DbSet<Book> Customers { get; set; }
public DbSet<Order> Orders { get; set; }
}

entity framework code first and view mapping

I have a application using code first; in search section I have to gather information from 3 tables and their related tables so I made a view; and since there is no syntax for code first to create view (I think so; please let me know if I'm wrong) I used pure SQL script;
on model creating to prevent EF to create a table with same name as table (VIEW_SEARCH) I did :
protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
modelBuilder.Ignore<View_Search>();
}
any ways application works fine until you try to get data from the view then BANG...
The model backing the 'SearchContext' context has changed since the database was created. Consider using Code First Migrations to update the database (http://go.microsoft.com/fwlink/?LinkId=238269)
This error simply says that what you have in your model file is inconsistent with what you have in your database.
To make it consistent go to Package Manager Console and type Enable-Migrations, then Add-Migration yourMigrationName and Update-Database. The error should disappear.
If you want to combine data from 3 tables you can simply create a ViewModel.
Let's say you have 3 models: Book, Author, BookStore and you want to have all information in one view. You create ViewModel
public class MyViewModel
{
public Book myBook {get; set;}
public Author myAuthor {get; set;}
public BookStore myBookStore {get; set;}
}
Then you add at the top of your all-in-one-view
#model myNamespace.MyViewModel
and access items like
Model.Book.title
Model.Author.name
Model.BookStore.isClosed
I'm actually working with Entity Framework "Code First" and views, the way I do it is like this:
1) Create a class
[Table("view_name_on_database")]
public class ViewClassName {
// View columns mapping
public int Id {get; set;}
public string Name {get; set;}
// And a few more...
}
2) Add the class to the context
public class ContextName : DbContext {
// Tables
public DbSet<SomeTableClassHere> ATable { get; set; }
// And other tables...
// Views
public DbSet<ViewClassName> ViewContextName { get; set; }
// This lines help me during "update-database" command
protected override void OnModelCreating(DbModelBuilder modelBuilder) {
// Remove comments before "update-database" command and
// comment this line again after "update-database", otherwise
// you will not be able to query the view from the context.
// Ignore the creation of a table named "view_name_on_database"
modelBuilder.Ignore<ViewClassName>();
}
}

Map names for generated relationship tables in EF code first

I'm giving Code first a try and I have the requirement of a prefix of (all) my tables in db.
In my DbContext I have these entities:
public DbSet<Person> People { get; set; }
public DbSet<Department> Departments { get; set; }
I can successfully map table names for my entities by overriding:
protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
modelBuilder.Entity<Person>().ToTable("w_people");
modelBuilder.Entity<Department>().ToTable("w_departments");
}
However for tables that created that don't directly map to a table I can't figure out to prefix.
In my example people can belong to many departments so a "non-entity" table is created by EF. (I'm a EF noob so these tables probably have a fancy name) So in my db I get three tables:
w_people
w_departments
PersonsDepartments
The PersonsDepartments table is what I'm after. How can I prefix these generated tables or change name/mapping after generation?
TIA
I have solved this:
modelBuilder.Entity<Person>().HasMany(p => p.Departments)
.WithMany(d => d.People)
.Map(mc => mc.ToTable("w_peopledepartments"));

Entity framework code-first ignores table mapping

We have a ef project using an existing legacy database, but adding new tables to it using ef-migrations. For these entities, we create tables using a new schema, to separate them from the legacy tables. We use the convention with plural form of the class name on the db tables.
However, when we add a new class to be mapped to a legacy table (without a plural table name), ef seems to ignore the mapping.
The entity class:
public class Aktor:IVersionedEntityWithId
{
public int Id { get; set; }
public string Navn { get; set; }
public byte[] Version { get; set; }
}
The mapping code:
protected virtual void MapAktor(EntityTypeConfiguration<Tilsyn.Domain.Aktor> config){
config.ToTable("dbo.Aktor");
config.Property(v=>v.Version).IsConcurrencyToken().IsRowVersion();
config.HasKey(e=>e.Id);
}
The exception:
System.Data.EntityCommandExecutionException: An error occurred while
executing the command definition. See the inner exception for details.
---> System.Data.SqlClient.SqlException: Invalid object name 'dbo.Aktors'.
It seems like the sql generated still ad an s to the class name to get the table name. What is missing in this picture? Am I using the ToTable method wrong?
Update: When changing the class name to something other than the table name, it seems to work. When changing the name back again, the problem has vansihed. Is there a EF cache or hidden mapping file somwehere?
Try overriding OnModelCreating() method in your DBContext subclass to create your mappings.
protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
modelBuilder.Entity<Tilsyn.Domain.Aktor>().ToTable("dbo.Aktor");
}