I have two extended instances of DbContext that I use in my code-first solution. One is only ever read only as it maps to an existing set of tables for demographic purposes. The other context is mapped to a local working set of tables.
I have created a view and mapped it to its own entity that is included as a navigational property in a POCO model representing an entity that's mapped to the other context. So my question is: can I use Include to fetch related entities across contexts? So far this doesn't appear so as it complains that it's looking for the view under the wrong schema - the one used for the other context - even though the view clearly has the correct schema defined in its mapping.
I'm using EF 6 with MVC 4.
Each context runs in complete isolation and you cannot share objects from one context to the other. Even if you pull the objects from the database in notracking mode, the moment you associate those objects in the other context by assigning them to navigation properties you are effectively pulling them into the other context which you don't want.
If you have a readonly context of some kind then what you can do is only fill in the foreign keys ids in the read/write context.
Related
The goal
My goal is to create a hierarchy of DbContexts each one residing in different assembly. Whatever references are required are established correctly so that the C# code compiles successfully.
The scenario
Let's say I create a db context, e.g. DbChild, inheriting from a base one, say DbBase.
The base context has some entities defined in OnModelCreating(). A migration for these entities is created and successfully applied to the database, thus the db schema contains the DbBase model mapped.
Needless to say DbChild uses the very same connection string and therefore the same database (I tried a number of ways to supply the connection string, the last one specifying it directly in optionsBuilder.UseSqlServer("<conection string>");).
Actual result
Creating a migration for the child context, however, includes the base model as part of the child one, which results in duplicate SQL objects in the DB.
Required result
A "clean" migration including only SQL objects (EF entities) from the child context is required.
Any ideas how to achieve this?
Thanks in advance.
PS: calling Ignore(...) in OnModelCreating() might be a workaround but it needs everything referenced in DbBase to be referenced in DbChild which is not an option.
PS2: Totally ignoring the base model while create the child one is not an option too - child uses an entity from base as a relationship.
EDIT: The snapshot <ContextName>ModelSnapshot.cs contains a "copy" of the model which gets updated with each migration. This is where every migration starts up. In complex models, however, it would be much easier, and what is much more important - safe, to have the snapshot file generated programmatically out of the existing database instead of copying, changing namespaces, renaming so as to have the context name reflected etc.
So, the questions may be transformed to "How to generate database snapshot when applying the first migration?".
Any ideas are welcome.
When creating a new derived context, after setting up the DB connection string but before adding any derived types to the context, you should create a migration that saves the snapshot of the pre-existing base context types.
In EF6, this would be done by creating a migration with Add-Migration PreExisting –IgnoreChanges. This produces a migration, where the internal model contains an updated snapshot, but the Up and Down methods of the migration are empty.
I'm not up to date on whether EF Core does support the -IgnoreChanges switch currently. According to What is the equivalent of the -IgnoreChanges switch for entity-framework core in CLI?, an alternative is, to manually clear the Up/Down methods after creating a migration.
Only after the first snapshot migration is created, start with adding additional entities to the derived context and creating migrations to add them to the database etc.
I'm working on a project which uses NHibernate as an ORM.
A fairly large number of entities can be loaded into the session as 'readonly' since they should not be updated after retrieval.
I've tried to do this in 2 different ways:
var entity = criteria.UniqueResult<MyType>();
_session.SetReadOnly(entity, true);
or:
criteria.SetReadOnly(true);
In both ways however, I can see that the entity is present in the PersistenceContext of the ISession.
Is this normal ? I'd expect that, since the entity is readonly/immutable, it should not be present in the PersistenceContext.
The entity type is a complex type; it has multiple associations to other types.
There are some limitations to the Read-Only functionality in nhibernate. The name of the function lets one expect a harder warranty of preventing object changes.
If you look at the documentation (http://nhibernate.info/doc/nh/en/index.html#readonly) there are many exceptions that could lead to unintended changes in the database.
From the docs:
When an entity is read-only:
NHibernate does not dirty-check the entity's simple properties or
single-ended associations
NHibernate will not update simple properties or updatable
single-ended associations
NHibernate will not update the version of the read-only entity if
only simple properties or single-ended updatable associations are
changed
In some ways, NHibernate treats read-only entities the same as entities that are not read-only:
NHibernate cascades operations to associations as defined in the
entity mapping.
NHibernate updates the version if the entity has a collection with
changes that dirties the entity;
A read-only entity can be deleted.
Considering your expectations it think Objects are always added to the Persistence-Context even if they are load Read-Only. Otherwise the Identity-Map -Pattern would not hold. In the Persistence-Context there is a Flag that signals that an entity is Read-Only.
In the context the state can be checked by opening the individual entity entry.
I am uploading a lot of data to a database using entity framework. I have a lot of different entities with relations between them.
My problem is that sometimes the object I'm uploading might already be in the database, but when I look up that object and find it, I can't add it to my locally made entities, because they belong to different contexts.
For example, I have the entities Sailor and Booze, which have a relation. I have a new sailor Ackbar and I know his favourite booze is rum and I want to persist this to the database.
I make a new sailor and set its name to Ackbar. Then I look up to see if Booze has an entry called rum. If it has, I try to add it to Ackbar. When I do this, EF complains that the new sailor and the booze from the database belong to different contexts.
If I try to attach sailor to the context, it complains that sailor has a null entity key.
How can I build all these relations without saving anything to the database before I'm done editing the relationships?
I suggest that you alter your code to use the same Context for reading and writing. Having multiple contexts for a single transaction is not a better option than having a Context that's alive for a few minutes.
Problem case:
My problem is editing disconnected POCO entities and then saving them to the database (Uisng Entity Framework). When doing so, the generated sql updates ALL properties even though only some have actually changed. When I do the same within the context, the generated sql correctly updates only the modified properties. This causes problem with my auditing code since it wrongly stores changes on all the properties. This is made worst when the entity I am persisting has a complicated model with many relationships.
My proposed solution:
Instead of attaching the modified entity to the context, I want to query the entity and then manually syncronize the two object with a generic method that will work for any model. So I need to compare all properties from each object and update the modified properties to the attached entity. How do I go about updating the values in the properties, keeping in mind that changes might include new or modified relationships ?
Any thoughts?
I have my domain split into multiple Entity Framework models. I have some shared entities that span multiple models (named Lookup), however, these are replaced with "using" references using the methods described in Working With Large Models In Entity Framework. However, what makes my case slightly more unique is that I'm also separating these models into multiple databases (one per model).
I'm having a problem inserting one of my shared entities into my common DB. It's failing with the error:
The member with identity
'Harmony.Members.FK_ResidentialAddress_ResidenceTypeLookup'
does not exist in the metadata
collection.
That foreign key that it's referring to does not exist on the "common DB". But I'm also not working with the entity on the other side of the relationship (named ResidentialAddress); nor do I even have the context that would contain the other entity initialized (named MembersDb). However, both models are compiled into the same assembly.
There are no navigation properties going from Lookup to ResidentialAddress. Though there is a navigation property in the other direction (which I won't be persisting - only using in memory).
My MetadataWorkspace for the EntityConnection of the CommonDb context was explicitly initialized with only the SSDL/CSDL/MSL for the data required for that database. I have confirmed there is no references to the foreign key mentioned in that set of schema data.
var metaAssembly = typeof(CommonDb).Assembly;
var schemaResources = new string[]
{
String.Format("res://{0}/Common.ssdl", metaAssembly.FullName),
String.Format("res://{0}/Common.csdl", metaAssembly.FullName),
String.Format("res://{0}/Common.mdl", metaAssembly.FullName),
}
MetadataWorkspace metadata = new MetadataWorkspace(schemaResources, new []{ metaAssembly });
EntityConnection connection = new EntityConnection(metadata, myDatabaseConnection);
POSSIBLE CLUE: It does work when I go into the generated classes and remove all of the EdmRelationshipAttribute attributes along with their paired EdmRelationshipNavigationPropertyAttribute from the related models (MembersDb).
Key questions:
So why is it that Entity Framework is trying to do something with the relationship that is for an entity that is neither in scope and nor will it be affected by the insertion of the record!?
I am happy to have the generated code remove the attributes mentioned above, but I still want the navigation properties to remain. How would I go about altering the CSDL to achieve that?
NOTE: Persistence of the "child" models is not a priority, nor is the integrity of their now cross-DB foreign keys. These databases are persisted using SQL CE but they were originally generated from a single master SQL Server database.
If each part of your model is written to a separate database, then perhaps the edmx files should not know about each other (about entities or relationship to entities that do not belong to them).
How about trying one of the following approaches:
(To end up with same entities classes for each part, but make EF oblivious of connections between them.)
Remove the "usings" from edmx + cancel auto generation and create classes yourself.
Remove the "usings" from edmx + modify t4 template to read more than one edmx when creating the classes.
Copy edmx files aside so you have two sets of edmxs.
3.a. Use set #1 for auto generation of entities.
3.b. Modify set #2 by removing the "usings" and use for generation of repository classes (objectsets).
Let me know if one of these works.
Good luck,
Danny.