简体   繁体   中英

Exclude or Ignore Property of an Entity model if column is not exist in database table

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?

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()
        {
        }
    }
}

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?

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.

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM