1

I want to create a read-only property [NotMapped]Database {get;} on a POCO entity class to reflect the name of the database from which the entity was loaded at the time of creation so that I can read the value later when no DbContext instance is available. How do I tell EF to load this data at object creation time?

I know about context.Database.Connection.ConnectionString, but that is not what I want to do. I want to set the property to the current database name when the object is being instantiated via a DbContext class.

I have searched for this problem but haven't been able to find any information to provide here, perhaps I don't know how to phrase the question.

2 Answers 2

2

You can do it like this. First create some interface:

public interface IHasDatabaseName {
    string Database { set; }
}

And implement for entity in question. Then in constructor of your DbContext (or at any place where you construct your DbContext, if you use DI container for example), subscribe to ObjectMaterialized event:

// this is DbContext here
((IObjectContextAdapter) this).ObjectContext.ObjectMaterialized += ObjectContextOnObjectMaterialized;

And then:

// this is DbContext here
private void ObjectContextOnObjectMaterialized(object sender, ObjectMaterializedEventArgs objectMaterializedEventArgs) {
    var dbName = objectMaterializedEventArgs.Entity as IHasDatabaseName;
    if (dbName != null) {
        dbName.Database = this.Database.Connection.Database;
    }
}
Sign up to request clarification or add additional context in comments.

Comments

0

I think you need to create a computed column on the table to fetch that information. Something like:

alter table YourTable add [Database] AS DB_NAME();

Then define your POCO property as Database {get;}.

1 Comment

I can't modify the storage layer and because I want this value on every class, that would be too large an undertaking.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.