简体   繁体   中英

When using Entity Framework Code First, is it acceptable to add properties to a class that are not mapped to a database table at all?

Just as the title states, Can I add an extra property to one of my POCOs that does not map to a DB column(database was created first), and will not be persisted. This property will only be used within the application and never needs to be persisted.

Are there any extra measures to take to accomplish this besides defining the property as normal?

Yes, you absolutely can do that. Here's an example from a configuration class I have:

public class ForCommentEntities:EntityTypeConfiguration<Comment> {
    public ForCommentEntities(String schemaName) {
        this.HasRequired(e => e.SystemUser)
            .WithMany()
            .Map(m => m.MapKey("SystemUserID"));
        this.Ignore(e => e.Remarks);
        this.ToTable("Comment", schemaName);
    }
}

The this.Ignore call is the important part. It takes a lambda expression to one of the properties on your class. This is part of what makes EFCF great (IMO) as it keeps configuration detail out of your POCOs.

The configuration class would be used like this in your Context :

protected override void OnModelCreating(DbModelBuilder modelBuilder) {
    base.OnModelCreating(modelBuilder);

    var schemaName = Properties.Settings.Default.SchemaName;
    modelBuilder.Configurations
        .Add(new Configuration.ForCommentEntities(schemaName))
        // ...other configuration options here
    ;
}

The nice part about Code First and POCO is you can now have business objects which are used by EF without the need of a mapper (eg AutoMapper or your own). Also means not having to decorate your objects with EF attributes and more (hence Yuck's answer above). However a additional advantage is, yes, the ability to add methods or properties to the object. An example would be a collection (eg addresses) and you would like to have a sorted or filtered projection. Another would be business rule validation before calling SaveChange(). As we all know, the possibilities are endless but the point is you can and should use these objects as business objects who get populated from your data layer.

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