I have a question about about proxy in NHibernate. I've inside in my log file a lot of logs like: Narrowing proxy to - this operation breaks ==
There are a few other questions on the web and different answer:
Stackoverflow NHibernate narrowing proxy warning It being a big deal or not depends on the level of risk you are willing to accept. Since there is going to always been a disconnect between your code and your database you can not always assure that the casting will work. This will lead to bugs that might be difficult to diagnose and may not be resolved without changes to the database or the code.
Another post from hibernate:
Narrowing problem Don't worry about his warning, just put the following in your log file and you shouldn't see it anymore...
Why it happens?
Suppose you have a Product with a many-to-one association to Address. Both are entities and Address has a ShippingAddress subclass.
Let's Session.get(..) a Product from the db that has ShippingAddress as association. Because the many-to-one is lazy, it will return a Address proxy. Note that this is a Address proxy and not a ShippingAddress proxy as the proxy will always match the type that is mentioned in Product (see the hibernate book for details).
This proxy is stored by Hibernate in his proxy cache.
Now we Session.get(...) the same ShippingAddress from the db, the one that is associated to the Product that we used fetched from the db.
Now Hibernate will see that it already contains a proxy for this ShippingAddress and will return this. However, it will notice that the types aren't the same so a "downcasting" must occur. Because this latter action isn't possible with "proxies" it will create new one and return it...
As you can see, nothing to worry about.
You could consider making the Address a value type...
In my case that's no option.
And a last one
ProxyWarnLog Removed in Hibernate 4?
Here is the code from NHibernate: StatefulPersistenceContext.cs -> NarrowProxy(..)
So, is it a problem or not? I always work with detached objects in my program.
I hope someone can help me.
Thanks a lot.
This can be a trouble if you use the == operator to compare entities and decide whether they are the same one or not.
This does similarly occur (but with Equals indeed) when you add an entity to a collection mapped as a set. If the set happens to already contain the entity but instantiated through another proxy type, the add may fail to respect its contract, it may add again the entity, and the set would then contains two occurrences of the same entity.
This is a may, not a will, because you can avoid this trouble by overriding Equals (and GetHashcode, as it is mandatory to return the same hashcode for objects being equal) on your entities, in order to compare them through their primary key and entity type. For set, it is sufficient (since it do not use the == operator, but the Equals method, prioritizing the one from IEquatable<T> if your type implements it).
For ==, you need then to define the == and != operators on your class for using your Equals implementation.
Read here or here for more on this. Beware, their example implementations are just examples, and are not suitable for a domain model using inheritance. Read here for a overriding example handling inheritance. (But it does not handle transient entities: better append to it a final test on natural ids if they have one, rather than yielding false if both are considered transient while being not the same reference.) And this blog provides a base class with == redefined (found in this Stack Overflow question).
Working with detached entities increases this risk. If you have not already overridden those two methods on your entities, it would be safer to do it, regardless of this warning.
Related
I have quite some entities in the DB and all of them have a column decimal DBSTATE indicating if the entry is active (1) or not (0). To make a quick work of getting the instances, I created the following generic function that returns only the active columns of entities:
IEnumerable<DBType> GetActiveEntries<DBType>()
where DBType : class, IDBEntry
{
return db.Set<DBType>().Where(e => e.DBStateInDB == (decimal)DBState.Active).AsEnumerable();
}
IDBEntry is an interface that all the model classes implement by returning its DBSTATE value, e.g. this is how REGULARCUSTOMER implements it (irrelevant parts are omitted):
public decimal DBStateInDB => this.DBSTATE
As it turns out, this is not possible, because EF can only work with its own types in queries, this is why the following non-generic function works:
IEnumerable<REGULARCUSTOMER> GetActives_TEMP()
{
return db.REGULARCUSTOMERs.Where(e => e.DBSTATE == (decimal)DBState.Active).AsEnumerable();
}
So my question: is it possible to somehow avoid writing separate functions/switch-cases for all the entities or I really stuck with that option?
I'd say you have to go around the problem.
One possible way of doing it would be to add Navigational properties (by creating a new entity type) to your entities, as DbSet<EntityState> (for example) which your entity would have a ForeignKey defining the State, this would oblige you to have a supplementary table which would contain the ID's of every entity and a bool for their state, making it clean and accessible. This also means that with your newly created Navigational property you could access it with YOUR_ENTITY.EntityState.State or YOUR_ENTITY.EntityState.Id, it would also give you the capacity to modify/access a entities State regardless of their type because of the new table. Your type enherited rules will still apply and changing the table will change the entity, regardless of Type.
But again, this is only a way of doing. It should be relatively simple to implement and can be quite powerful.
Let me know what you think.
I have a Candidate class. When somebody deletes a Candidate, I want a DeletedCandidate which is derived from Candidate to be stored in a separate table.
How can I model this in EF, Code first? I think my best option is TBC, but when I use the following in Context, a System.Data.MappingException is thrown.
modelBuilder.Entity<DeletedCandidate>().Map(d => {
d.ToTable("DeletedCandidate");
d.MapInheritedProperties();
});
I would not use inheritance for archiving-like tasks. You will always have to make a distinction between Candidates and DeletedCandidates in your mainstream application code. With EF you'll have to do that by always retrieving candidates by OfType<Candidate>.
I would make a separate class (and table) for DeletedCandidates. Thus, you can always get to them when needed, but they never get in harm's way in the rest of your code. A drawback may be that you always have to keep the properties (and columns) of the two in sync. This could be relieved by having both classes implement a common interface (which you can easily do with code-first).
If you need to preserve foreign key relationships to DeletedCandidates it's a different story. In that case I think the best you can do is using a deleted flag (but you're going to need filtering to get the active candidates).
Just an advice :D.
I've found one that allows multiple fields of type long. However, i'm not sure how useful that is since sometimes we may have Guids or even dates for example.
I could also modify his to support my needs, but this seems like it would be such a common request that I should be able to find something tested, tried and true instead of creating it from scratch.
The main purpose i have behind this is use the Identity Map pattern. I believe this pattern more or less requires the Identity Field pattern to support it. I will use the Identity Field construct as the key to my dictionary
Any ideas?
Thanks
I think to implement a similar pattern for a multi-column PK, you would just need to create a field/property on your class for each of the PK columns on the table.
For example, if you had a "Message" table with a PK with a long, a guid, and a datetime, your class would just need to include a long, Guid, and a DateTime property.
You would probably also want to implement Equals() and GetHashCode() for the object using these PK fields, because you want these objects to compare in database terms, not in terms of the in-memory address of the object. GetHashCode is important, because you want to ensure that Objects with the same PK properties produce the same hash code. To implement GetHashCode, I would recommend looking at Jon Skeet's answer here: What is the best algorithm for an overridden System.Object.GetHashCode?
Fowler's "Identity Field" pattern maybe assuming that your tables have a single surrogate PK column, and that is why he specifies it the way he does.
Check out S#arp Architecture. When you inherit from their Entity object, you can decorate as many properties as you want to with the DomainSignatureAttribute. These properties will then be considered as the object's identity in the implementation of Equals and GetHashCode that is provided in Entity.
Just need to clarify this one, If I have the below interface
public interface IRepository<T>
{
T Add(T entity);
}
when implementing it, does checking for duplication if entity is already existing before persist it is still a job of the Repository, or it should handle some where else?
Yes - I recommend doing these checks in the repository.
Long answer: The term "repository" is a bit vague, but it is used more and more as the name of the persistence abstraction layer. The name is nice, but does not say too much: If you take Asp.Net MVC as an example, the sample apps, like Neirds dinner and alike, or codeplex projects encapsulate data access by the repository class. If such layer is implemented with a relational database for instancce, the primary keys of the tables will not allow duplicate entries, which means that in this case the repository implementation will throw an exception if 2 entries with the same key are inserted. So in other words, a RDBMS-implementation of a repository will quite always due this check, you wont be able to avoid it. So to make the behavior of repostories out there in the world most similar and to avoid surprises, lets all of them do this check.
It is a second question whether you should maintain in the business logic already that your Add() method is not alled with an entry that already exists. Sometimes it makes good sense to resolve this only at a single point, the database for instance, due to concurrency issues or savings of roundtrips. On the other hand it is for instance nice to tell the user as soon as possible that a username is already taken. So this depends.
have a nice day
If the entity already exists, you can either throw an exception, or update the existing entity's fields.
If you choose the latter, the method should probably be called something like AddOrUpdate()
Linq to SQL example
If I am retrieving a single record, I will use
public Entity GetEntity(int entityID)
{
return dataContext.Entities.SingleOrDefault(e => e.EntityID = entityID);
}
...And in the calling method, I will check to see if what is returned is null before attempting to use the returned entity.
If I am updating a record, I will retrieve the entity as shown, edit the entity, and then call an UpdateEntity(entityID) repository method to update the fields in the database.
If I am adding a record, it's even easier. Since this is a database, and my tables always contain an Identity field of type int (an auto-assignable number, essentially), adding a record is the simplest operation of all (it's always a new record):
Public void InsertEntity(Entity entity)
{
dataContext.Entities.InsertOnSubmit(entity);
dataContext.SubmitChanges();
}
Business rules (email addresses are unique, for example) can be handled in the repository, or in a separate business layer. If you are looking for the most "correct" way, I think most people would agree that business rules belong in their own Business Logic Layer.
Essentially the decision on where to handle that case depends on your exact requirements.
If you have business rules that define clear cut actions for when this happens, eg if a duplicate exists the new item should be renamed, then it can be built into the repository class.
On the other hand, if more complex rules are in place whereby, for example, more information is required to change the item before adding, then it should be handled further up the food chain.
The concept of a repository states that it exists to perform the persistence activities.
So if you can do it all within the repository, that's fine. If you find you start to reference outside the repository, or your repository has dependencies, eg calling another repository, or a service, or a manager (or whatever processor nomenclature you prefer), then it's a good sign to take it back a step.
I am seeing in some domain object models that an abstract base class is created(that implement Equals and GetHashCode) for all domain Entity objects to inherit from to gain their identity.
I am not clear why this base class is needed and when and why it should be used. Can you provide me some insight on this or refer me a link that talks on this
Thanks
Now I understand the advantages of overriding Equality (this link helped http://en.csharp-online.net/CSharp_Canonical_Forms—Identity_Equality)
Going back to domain driven design I would like to expand my question a bit;
I have a customer entity which I use guid as identity.
If I create 2 instances of customer with exactly the same details, since I am using guid as the identity they will be two different objects. But as they have all attributes the same they should be the same object(or is it a better ddd practice to keep them unique and seperate??)
Trying to understand if I should handle the equality of two objects by their full attribute value match. If I go toward that direction then I am looking at either overriding the Equality of the base class on the level of sub class and implement these conditions or have the identity of the entity a string or hash code(?) representation of the values of all these attributes and use the Equality of the base class.
I could be little off here so thanks in advance for the patience.
The use of the term equality is overloaded here:
1) Equality for Identity
If you have 2 instances of the same Customer, they should both have the same GUID value – it’s the only way to ensure that you're working with the same Entity. In reality, there will always be different instances of the same Entity (e.g. multi-user apps running on different machines).
2) Equality for sameness
This is where you're checking that 2 instances have all the same values. For instance, if 2 staff members are looking at the same Customer, and the first person modifies & saves it, both people will see different data. They’re both interested in the same Customer, but the data becomes stale.
For (2), you definitely need a mechanism to do the checking. You could compare each property (expensive), or you could use a ‘version’ property to detect changes (see NHibernate’s optimistic locking mechanism).
I think your example is a bit contrived, and might be drawing you away from the more important aspects of DDD. If you’re interested, I sell a tool that can help grasp DDD concepts easier.
You should compare the IDs of the objects if they are entities and their attributes in case they are value objects. That means that you don't have to inherit your value objects from a base entity, but for entities it's better to create one.
How to understand if a class is an entity or a value object? You should answer a question: are objects of such class equal if they have the same attribute set? If yes, they are values objects. For example, two persons are not equal even if they have the same names and birth dates - you should treat them as different entities anyway. But if you have 25 cent coin, you probably don't care what exact piece of metal do you have, they all just 25 cent coins.
There's a great article describing the details: domain object base class
If you are following DDD, I believe you should check on the equality of the objects by their ID (Identity). This is because domain entities are primary defined and tracked by its identity and not by attributes. So no matter how similar they are with other objects, they are still diffirent entities.
Another concept that you would want to check out is a value object. It is something that describes a charasteristics of an object and doesn't require an identity. Example would be, address, money, color.
You pointed at two of the reasons of why it is used.
For Equals you may not want to always check if the actual reference is equal, because it may not be. You may want to use some sort of identifying property (like public int ID) to check against to see if 2 entities are equal. The base implementation of Equals is just going to check if the 2 references are equal.
As far as hash code it's a way to uniquely identify a given object/type when using it in hash algorithms etc.
I would have equals only check on identity, because it allows you to have an instance of an entity containing a before and after situation, which can be very handy at times. To check if an instance has changed, a Dirty flag can do the trick.
HTH,
Jonathan