Reputation: 590
I have added new property in my Entity Model as the new column has got added in DB table. But In that column might or might be there in other client database. So, How handle this? I have tried modelBuilder.Entity<Customer>().Ignore(customer => customer.FullName);
But it's not ignoring the property in entity. Because we have entity mapped class so it is not ignoring it.
Solution please?
Upvotes: 5
Views: 15515
Reputation: 91
If you add the [NotMapped]
attribute, Entity Framework will not create a column for it:
using System.ComponentModel.DataAnnotations.Schema;
namespace DomainModel
{
public partial class Customer
{
public int Id { get; set; }
public string Name { get; set; }
[NotMapped]
public string FullName { get; set; }
}
}
Or if you want to map the column, but in some databases it already exists, here's a migration which will add the column only if it does not exist.
namespace DataAccess.Migrations
{
using System;
using System.Data.Entity.Migrations;
public partial class AddFullNameToCustomer : DbMigration
{
public override void Up()
{
Sql(@"IF COL_LENGTH('Customer', 'FullName') IS NULL
BEGIN
ALTER TABLE Customer
ADD [FullName] varchar(200) null
END");
}
public override void Down()
{
}
}
}
Upvotes: 3
Reputation: 27888
Just stop it. You're creating a world of pain for yourself.
If you want to have a dynamic schema, then you shouldn't be using Entity Framework at all.
Simplify and avoid all this headache by creating a migration that ensures that the field gets created in every single database (so that at runtime, the context will always match the database) and make sure the migration is executed before the app runs.
Upvotes: 0