Changing column name convention in code-first EF4 - c#

I'm using EF4 with CodeFirst.
public class MyContext : DbContext
{
protected override void OnModelCreating(ModelBuilder modelBuilder)
{
base.OnModelCreating(modelBuilder);
modelBuilder.Conventions.Remove<XXX>();
modelBuilder.Conventions.Add<XXX>());
}
}
What convention should I add or remove to make all DB identifiers (like column names, table names, stored procedures etc) to be in uppercase (or unquoted)?
Case-sentitive (quoted) identifiers in Oracle DB greatly suck in user-friendliness.

Consider the Product and Customer class
public class Product {
public int Id { get; set; }
public string Name { get; set; }
public int Stock { get; set; }
}
public class Customer {
public int Id { get; set; }
public string Name { get; set; }
}
public class MyDbContext : DbContext {
public DbSet<Product> Product { get; set; }
public DbSet<Customer> Customer { get; set; }
public MyDbContext() { }
protected override void OnModelCreating(System.Data.Entity.ModelConfiguration.ModelBuilder modelBuilder) {
modelBuilder.Conventions.Remove<PluralizingEntitySetNameConvention>();
modelBuilder.Conventions.Add<TableNameUppercaseConvention>();
base.OnModelCreating(modelBuilder);
}
}
public class TableNameUppercaseConvention : IConfigurationConvention<Type, EntityTypeConfiguration> {
public void Apply(Type typeInfo, Func<EntityTypeConfiguration> configuration) {
configuration().ToTable(typeInfo.Name.ToUpper());
}
}
EDIT:
I tried to do something like this, but it seems that doesn't work, idk why
public class ColumnUppercaseConvention : IConfigurationConvention<MemberInfo, PrimitivePropertyConfiguration> {
public void Apply(MemberInfo memberInfo, Func<PrimitivePropertyConfiguration> configuration) {
configuration().ColumnName = memberInfo.Name.ToUpper();
}
}
my best approach was
public class Customer {
[Column(Name = "ID")]
public int Id { get; set; }
[Column(Name = "NAME")]
public string Name { get; set; }
}
sorry, I can't help right now, but I'll keep trying.

I don't know how can you do this with conventions but take a look at StoreNameAttribute. You can apply on context, entities and properties.
Data Annotations in Entity Code First

Related

Dictionary realization for multiple tables in EF Core

I have so strange question connected with realization of dictionary (handbook, etc.) with description of, for example, work types. Let me explain.
Let me have 2 classes:
public class Order
{
public Guid Id { get; set; }
public ICollection<WorkType> WorkTypes { get; set; }
}
public class PurchaseOrder
{
public Guid Id { get; set; }
public ICollection<WorkType> WorkTypes { get; set; }
}
where
public class WorkType
{
public int Id { get; set; }
public string Description { get; set; }
}
and my context is:
public class MyDbContext : DbContext
{
public DbSet<Order> Orders { get; set; }
public DbSet<PurchaseOrder> { get; set; }
protected override void OnModelCreating(ModelBuilder modelBuilder)
{
base.OnModelCreating(modelBuilder);
}
}
When I make a migration, I get 2 additional columns in my WorkType table: OrderId and PurchaseOrderId.
So, I don't want to have them in this table, of course. Is it possible to make this N:M relation without FK?
Possible I can have WorkType collections in many classes.
Thank you.
P.S. I use EF Core 6.0.6

Many-Many relationship in EF6 with other colums in mapper class

I have existing tables including the mapper table. I have to set the Entity Framework annotations. I am confused about how to achieve that. there are three tables,
Model (ModelId, ModelName),
Department (DepartmentId, DepartmentName)
ModelDepartmentMapper (ModelDepartmentMapperId, ModelId, DepartmentId, ModelStatus)
I have created the classes as:
public class Model
{
public int ModelId { get; private set; }
public string ModelName { get; private set; }
public virtual ICollection<Department> Departments { get; private set; }
}
public class Department
{
public int DepartmentId { get; private set; }
public string DepartmentName { get; private set; }
public virtual ICollection<Model> Models { get; private set; }
}
public class JoinModelDepartment
{
public int JoinModelDepartmentId { get; private set; }
public Guid ModelId { get; private set; }
public Guid DepartmentId { get; private set; }
public int ModelStatus { get; private set; }
}
And in DBContext:
protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
//base.OnModelCreating(modelBuilder);
modelBuilder.Entity<Model>()
.HasMany<Department>(s => s.Departments)
.WithMany(c => c.Models)
.Map(cs =>
{
cs.MapLeftKey("ModelGuid");
cs.MapRightKey("DepartmentGuid");
cs.ToTable("JoinModelDepartment");
});
}
Please guide me how to add ModelStatus in the mapper table. Do I need to create it manually or there is a way to do this?
What I would tend to do is move these kinds of mappings into their own class files. Theres a brilliant tutorial found here:
https://www.entityframeworktutorial.net/code-first/move-configurations-to-seperate-class-in-code-first.aspx
This lets you map out each of the tables individually and it will build the database off of them.
So in your case you would have a Model, Department and a ModelDepartmentMapper class file. From there you can set all the relevant columns and how they are linked to another table as well as column types IE VARCHAR etc

EF model with list of objects

I'll create app to saving gym results.
I have class Exercise:
public class Exercise
{
public Guid Id { get; protected set; }
public string Name { get; protected set; }
public Category Category { get; protected set; }
}
and class TrainingPlan which contain List of Exercise :
public class TrainingPlan
{
public Guid Id { get; protected set; }
public string Name { get; protected set; }
public IEnumerable<Exercise> Exercises { get; protected set; }
}
I create EntityFramework DbContext:
public class GymContext : DbContext
{
public GymContext(DbContextOptions<GymContext> options) : base(options) { }
public DbSet<Exercise> Exercises { get; set; }
public DbSet<TrainingPlan> TrainingPlans { get; set; }
}
And then I used command add-migration and update-database. For table with exercise, EF was added additional field with TrainingPlanId. So now I can assignee Exercise only to one TrainingPlan. But I want assigne Exercise for a few Plans, what is the best solution for this case?
Thx for help, I use many to many.
It's solve, I crate new class:
public class TrainingPlanExercise
{
public Guid TrainigPlanId { get; protected set; }
public TrainingPlan TrainigPlan { get; protected set; }
public Guid ExerciseId { get; protected set; }
public Exercise Exercise { get; protected set; }
}
And in TrainingPlan I replace List of Exercise to List of TrainingPlanExercise.
My EntityFramework DbContext now look that:
public class GymContext : DbContext
{
public GymContext(DbContextOptions<GymContext> options) : base(options) { }
public DbSet<Exercise> Exercises { get; set; }
public DbSet<TrainingPlan> TrainingPlans { get; set; }
public DbSet<TrainingPlanExercise> TrainingPlanExercises { get; set; }
protected override void OnModelCreating(ModelBuilder modelBuilder)
{
modelBuilder.Entity<TrainingPlanExercise>()
.HasKey(e => new { e.ExerciseId, e.TrainigPlanId });
modelBuilder.Entity<TrainingPlanExercise>()
.HasOne(x => x.TrainigPlan)
.WithMany(x => x.Exercises)
.HasForeignKey(x => x.TrainigPlanId);
}
}
Unfortunately I'm stuck again. When I want get from DB single record TrainingPlan using this method:
public TrainingPlan Get(Guid id)
=> _context.TrainingPlans.Include(x => x.Exercises).Single(x => x.Id == id);
I receive record with null Exercise in List TrainingPlanExercise.
Should I add something more to DbContext or is there other solution?
BTW. I using EF core.

How to have multiple tables with the same schema in Entity Framework?

I'm trying to have multiple tables with the same schema, within the same database, using Entity Framework.
For example, if I have the classes below, and I login to the SQL Server database, I can only see a table that is named something like dbo.Schema.
Is there a way to have multiple tables with the same schema?
class Context1 : DbContext
{
public DbSet<Schema> table1 { get; set; }
}
class Context2 : DbContext
{
public DbSet<Schema> table2 { get; set; }
}
class Schema
{
[Key]
public int EntryId { get; set; }
}
Is there a way to have multiple tables with the same schema?
You can either use Data Annotations or Fluent API to configure the table and schema name.
Suppose you have the following model:
public class Blog
{
public int BlogId { get; set; }
public string Url { get; set; }
}
Using Data Annotations, you could name it blogging.blogs:
[Table("blogs", Schema = "blogging")]
public class Blog
{
public int BlogId { get; set; }
public string Url { get; set; }
}
Using Fluent API, you can override OnModelCreating method to name it blogging.blogs:
class MyContext : DbContext
{
public DbSet<Blog> Blogs { get; set; }
protected override void OnModelCreating(ModelBuilder modelBuilder)
{
modelBuilder.Entity<Blog>()
.ToTable("blogs", schema: "blogging");
}
}
You can simple do like this with multiple tables.
public partial class AdventureWorksEntities : DbContext
{
public AdventureWorksEntities()
: base("name=AdventureWorksEntities")
{
}
protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
throw new UnintentionalCodeFirstException();
}
public virtual DbSet<Address> Addresses { get; set; }
public virtual DbSet<AddressType> AddressTypes { get; set; }
public virtual DbSet<Contact> Contacts { get; set; }
public virtual DbSet<ContactType> ContactTypes { get; set; }
public virtual DbSet<CountryRegion> CountryRegions { get; set; }
public virtual DbSet<StateProvince> StateProvinces { get; set; }
}
in this code we can add more table from same database. There is no need to create another class and inherit DbContext.
or you can do Add Item into project-> New Item->Data->ADO.NET Entity Data Model.
This will generate same code with your selected tables.
Thanks

One-to-one relationship Entity Framework

I have two tables one with a list of clients and the other whether they are active or not. I want to link them Entity Framework, however, I am struggling. The two tables were already setup and have to primary keys or foreign keys.
namespace DataWarehouse.Models
{
public class DatabaseList
{
[Key]
public string STARDB { get; set; }
public int DBClientID { get; set; }
public string ClientName { get; set; }
public DatabaseStatus DatabaseStatus { get; set; }
public ICollection<PayComponents> PayComponents { get; set; }
= new List<PayComponents>();
}
public class DatabaseStatus
{
[Key]
public string STARDB { get; set; }
public string STATUS { get; set; }
public DatabaseList DatabaseList { get; set; }
}
public class DatabaseContext : DbContext
{
public DatabaseContext(DbContextOptions<DatabaseContext> options)
: base(options)
{
}
public DbSet<DatabaseList> DatabaseList { get; set; }
public DbSet<DatabaseStatus> Status { get; set; }
public DbSet<PayComponents> PayComponents { get; set; }
protected override void OnModelCreating(ModelBuilder modelBuilder)
{
modelBuilder.Entity<DatabaseList>()
.HasOne(p => p.DatabaseStatus)
.WithOne(i => i.DatabaseList)
.HasForeignKey<DatabaseStatus>(k => k.STARDB);
}
}
}
I was hoping that Entity Framework would see the columns STARDB and notice that it is the same in both tables and match them that way. All I want to is to add the Status column from DatabaseStatus into the Databaselist table.
Thanks.
Managed to figure it out. My database was setup properly. However, I forgot the include statement in my Repository.cs class.
public IEnumerable<DatabaseList> GetAllClients()
{
_logger.LogInformation("Get all clients was called");
var clients = _ctx.DatabaseList
.Include(d => d.DatabaseStatus)
.OrderBy(p => p.ClientName)
.ToList();
return clients;
}
Still new to C# so a bit of learning curve!

Categories

Resources