I started using RavenDB and I am getting concurrency exceptions when I am creating an entity and linking the entity to another entity, for examples:
Class - List students - string is the student id
Student
When creating a new student I am fetching the related class and adding the student to the "students" list. I saw that this storing and adding this relation is my bottleneck in my application.
How I can fix this concurrency problem? or maybe I can do this linking in other way? or update the Class with PatchRequest and then I won't have problems with concurrency?
You have two options
Retry on concurrency failure
Reduce contention on the Class entity.
Really, you have a many-to-many relationship between students and classes - so you can store the related key on either side of the relationship (or both sides if desired).
If your app works more frequently with classes than students, try putting a list of ClassIds on each student. You can still get back a list of all students in the class via a query.
Aside - I suggest "Course" instead of "Class" to avoid stepping on keywords in c#
Related
I have an inheritance strategy Table per Type (TPT) with an abstract class "Task" with a lot of concrete classes (like 30 classes).
When I try to show a worklist of "to do tasks", so asking EF for the abstract class, or when I try to get a generic task by ID, EF makes a 10000 lines query joining every concrete class, that result very slow.
There is a way to configure EF to avoid the big query?
In the worklist method, I need only fields of the abstract class.
This is my code:
public Task GetTaskById(int id) {
return this.repository.Tasks.Where(t => t.ID == id).FirstOrDefault();
}
public IQueryable<Task> GetWorklist() {
return this.repository.Tasks.Where(t => a.ActivitySate.Code == ActivitySateEnum.TO_DO);
}
Thank you
Relational databases don't handle the concept of inheritance very well. Several strategies have been invented for entity framework to mock inheritance.
Which strategy suits you most depends on which kind of queries and updates you perform most often.
Suppose you have a class Person, and two specific kinds of Persons: Teachers and Students. There are two popular strategies to implement inheritance
Table per Type (TPT)
Every class is represented in a separate table. In our example three tables are created: a Persons table, a Teachers table with a foreign key to the Person it is, and a Students table with a foreign key to the Person data of the Student.
If you query: "give me the Persons that ...", only one table needs to be inspected. However, if you ask: "give me the Students who ...", then a join between the Persons table and the Students table is needed.
If you add / update / remove one Student, then two tables need to be updated.
If in future one column needs to be added to one of the classes, only one table is involved.
Adding a new kind of Person, like Sponsors is easy, however they have to be Persons and inherit all Person columns. If later you decide that a Sponsor is not a Person anymore you are in trouble.
This method is most suitable if you ask far more often for Persons than for Students and Teachers. It is less suitable if you ask quite often for Students with Person data. Also if you add / remove / update Students very often, don't use this method.
Also use this method if you need to create a Person that is neither a Teacher nor a Student yet, but later may become one of them, or maybe both Teacher and Student
Table per concreate class (TPC)
There is no separate table for Persons. All Person properties are in the Teachers table as well as in the Students table.
Querying "Students who ..." or "Teachers that ..." will only involve one table. However querying "Persons that ..." will involve the concatenation of data retrieved from the Students table with data retrieved from the Teachers table.
Add / Remove / Update a Student will always involve one table.
Adding a column to a Student involves changing one table. However adding a column to Person involves changing both Students and Teachers tables.
Adding a new kind of Person, say Janitors or Sponsors is easy. It won't be a problem if in future a Sponsor is not a Person anymore.
You can't create a Person, it always has to be either a Teacher or a Student. A Student never can become a Teacher, he will become a new Person (which seems a bit ironic :-). No Student can be a Teacher as well.
Use this method if you seldom ask for Persons who ..., but most often ask for Students who ...
Conclusion
The strategy to choose for your inheritance depends on how you will use your tables.
You seem to have 30 kinds of Persons implemented as TPC (no separate Persons table). If you ask for Persons who ..., your database has to concatenate the results from all 30 tables.
If you think this is by far the most used kind of query, consider changing the inheritance strategy to TPT. Whether you should do this depends on whether the database is already filled with a lot of data or not. If you are using code-first, you'll probably start with a fairly empty database.
The problem is that you use a ba repository that does not return IQueryable, so it doesn ot allow EF to actually use the filters you DO have (you do, right?) where you limit the returned data to only some fields.
So, what is lett is materialize the entity (which is SOOOO standard for the repository antipattern). And there you go.... for that.... It NEEDS to join TPT. Those are 30 classes, which mean 30+ tables. First, the query likely has no 10k lines. Second, this is normal and smallish for really complex SQL (which you DO have here). Third, you set that up yourself - yes, this is what is needed to pull in all the data.
Solution? Get rid of the suplus repository (DbContext IS a repository, you know) and then make the filter based on the base type and make sure to project ONLY the needed fields into an anonymous class, so EF CAN do optimization.
New to NHibernate and C#.
I have these two classes:
User //Simplified version
{
private long _id;
private String _username; // unique
private ISet<Role> _roles;
//Properties
}
and
Role
{
private long _id;
private String _name;
//Properties
}
Is it better to store a reference to the Role class (as done above) or just store the IDs of the Role class (so: private ISet<Long> _roles)? Why?
Any pros and cons I should be aware of?
Well, firstly NHibernate is ORM.
... In object-oriented programming, data management tasks act on object-oriented (OO) objects that are almost always non-scalar values. For example, consider an address book entry that represents a single person along with zero or more phone numbers and zero or more addresses. This could be modeled in an object-oriented implementation by a "Person object" with attributes/fields to hold each data item that the entry comprises: the person's name, a list of phone numbers, and a list of addresses. The list of phone numbers would itself contain "PhoneNumber objects" and so on. The address book entry is treated as a single object by the programming language (it can be referenced by a single variable containing a pointer to the object, for instance). Various methods can be associated with the object, such as a method to return the preferred phone number, the home address, and so on....
Secondly - is it better to do A or B... would be more dependent on a use case.
But I can say, (based on my experience) that if:
there are two objects in our domain, e.g. User and Role
we can represent them as one-to-many andmany-to-one` (bidirectional mapping)
I will always map them via references. Because there is no benefit to map them as long ReferenceId and ISet<long> ReferenceIds.
The only use case where to map just IDs (I can imagine) would be to use it in stateless session to get some huge amount of data. But even in this scenario, we can use projections.
"Storing" the Ids doesn't sound like a good idea to me. In fact, the database schema would look the same, so it's not a difference how you store data, just how you design your classes. And ids aren't very useful in contrast to actual objects.
Here some pros and cons anyway:
Advantage of mapping IDs
You could serialize your entity more easily, because the object graph ends here and you wouldn't end up in serializing too many objects. (Note that serializing entities has some other issues and is not recommended in many cases.)
Advantages of mapping objects:
You can easily navigate to the objects without DB interaction thus taking full advantages of using an ORM (maintainability).
You can make use of batch size, which avoids the N+1 problem without optimizing data access in your problem domain (performance and maintainability)
When you build the domain model it should use the proper references rather than using id values,
Advantages,
You can have a proper domain model, so programming becomes easier (if you want to get list of role names per user, then in domain model it's pretty straightforward while if you have id list then it
Easy to query (using either QueryOver / Linq or HQL)
Efficient SQL (if you want to load the user and roles, you can use Future to load all in a single query if you use references, but if you use Id then you have to use multiple queries)
I don't see any disadvantages of using references as long as mapping is correct.
However I'd rather use Id of entities or a DTO stored if the requirement is to store a object over multiple sessions. For example if you want to store the user in the Web Session object, I would not store any domain objects there rather I'd store the Id or a DTO object.
I was hoping someone could give me a bit of advice here. I am wondering if I am on track or way off base in my approach. I am using Entity Framework, database first approach. I have a link table that associates people to each other. Person 1 associated to Person 2 as a friend for example. (association_type holds a key value associated to a lookup table)
I noticed that Entity Framework creates two separate navigation properties.
[EdmRelationshipNavigationPropertyAttribute("IntelDBModel", "FK_a_Person_Person_t_Person", "a_Person_Person")]
public EntityCollection<a_Person_Person> a_Person_Person
[EdmRelationshipNavigationPropertyAttribute("IntelDBModel", "FK_a_Person_Person_t_Person1", "a_Person_Person")]
public EntityCollection<a_Person_Person> a_Person_Person1
In other parts of the application, I have successfully used Entity Framework to write data to the database. For example, I have a person to telephone relationship.
In the person to telephone scenario, I create a t_Person (p) object, then create a t_Telephone (t) object and use p.t_Telephone.Add(t);
That seems to work fine.
I am somewhat lost in terms of how to manage this person to person link table insert.
When saving to the database, I use foreach to iterate through the People objects.
foreach (t_Person p in People)
{ctx.t_Person.AddObject(p);
...
}
I know what person is associated to what person in this People object collection. However, I don't know how to utilize the t_Person navigation properties (a_Person_Person) to save the person1 and person2 values to the link table (a_Person_Person).
Any hints would be greatly appreciated.
I think the given situation will generally give you hard time when using EF, since you are linking two foreign key two one table with same Primary key, since the relationship or lazy loading would be difficult to handle you might get double records or wrong records, I would add another property to the t_person table like datecreated which would make the the EF treat t_person table as not an association, but as actual entity giving you more control over entity and insertion and deletion.
I have a frustrating situation owing to this little quirk of EF. Here's a simple demo of the behavior. First the DB schema:
As you see, RestrictedProduct is a special case of product, which I'm intending to make a subclass of Product with some special code.
Now I import to an EF data model:
Oops! EF saw that RestrictedProduct had only 2 fields, both FKs, so it mapped it as a one-to-many relationship between Product and Restriction. So I go back to the database and add a Dummy field to RestrictedProduct, and now my EF model looks much better:
But that Dummy field is silly and pointless. Maybe I could delete it? I blow away the field from the DB table and the entity model, then refresh the model from the DB...
Oh, no! The Product-Restriction association is back, under a new name (RestrictedProduct1)! Plus, it won't compile:
Error 3034: Problem in mapping fragments starting at lines (x, y) :Two entities with possibly different keys are mapped to the same row. Ensure these two mapping fragments map both ends of the AssociationSet to the corresponding columns.
Is there any way to prevent this behavior, short of keeping the Dummy field on the RestrictedProduct table?
I just came across the same issue, and as an alternative to putting the dummy field in your RestrictedProduct table to force the creation of an entity you can also make your RestrictedProduct.RestrictionId field nullable and EF will then generate an entity for it. You can then modify it to use inheritance and any subsequent "Update model from database" will not cause undesired nav properties. Not really a nice solution but a work around.
Let's walk slowly into your problem.
1st thing you need to decide is if the restricted product is
really a special case of product or is it a possible extension
to each product.
From your original DB Scheme it seems that any product may have
a relation to a single restriction however a single restriction
can be shared among many products.. so this is a simple 1 to many
situation which means that restricted product is NOT a special case
of product! Restriction is an independent entity which has nothing
to do with product in a specific way.
Therefore EF is correct in the 1st importation of your scheme:
1. a product can have 0 or 1 restrictions.
2. a restriction is another entity which can be related to many products.
I do not see your problem.
I am trying to come up with a database design that would work with Entity Framework 4 Code First. Actually, I have no experience yet of EF4 Code First but as I understand it, if I write the code, it will create the database and tables.
The issue is this. There are various types of auctions, they all have some common fields and some specific ones. In the code I envisage having a base abstract class called Auction and subclasses like LowestUniqueBidAuction and EnglishForwardAuction etc.
Nothing surprising there. The problem is that I imagine the database structure to mimic this. I imagine an Auction table and a LowestUniqueBidAuction table and a EnglishForwardAuction table. In the Auction table I imagine a foreign key into one of these two tables for each row depending on the type of auction that that row is. I also imagine another column in the Auction table with the name of the derived auction table (such as EnglishForwardAuction).
The problem is that whenever I've ever created a foreign key I've had to specify the name of the foreign table into which the key points (which makes sense). In this case, however, there is one of many tables that the key could point. So there are many issues here. Firstly, I could simply not use a foreign key and just use an ordinary field, but then the database will not be able to maintain data consistency for me. The second issue is how will EF Code First handle this? In other words, how will it know that if I ask for all EnglishForwardAuction rows from the Auction table that it should look at the column with the table name and then join on the EnglishForwardAuction table to get the extra fields?
Has anyone ever faced similar issues?
Thanks,
Sachin
This problem is solvable in Entity Framework in a number of ways - read up on how EF handles inheritance and what strategies are available.
There are basically three strategies how to handle this:
(1) Table per Hierarchy
You have only one single table, that represents all possible sub classes. Of course, this means, several rows (that only exist in a given subclass) must be nullable, since they don't show up / don't exist in super classes or other subclasses.
(2) Table per Type
Each subclass gets its own table, and by default, the sub-types table shares the PK with the base classes' table - e.g. PK = 1 in Auction will also be PK = 1 in EnglishForwardAuction. So your subclass tables reference the base table - not the other way around.
(3) Table per Concrete Type
Each concrete subclass (your separate auction types) gets its own table, but that table contains everything - all the columns, from that specific type, but also its base type.
Read more here:
Inheritance in the Entity Framework
Inheritance and Associations with Entity Framework Part 1
Entity Framework Modeling: Table Per Hierarchy Inheritance
Entity Framework Modeling: Table Per Type Inheritance
Searching for Entity Framework Inheritance and/or one of these strategies will reveal a lot more hits, too - that topic is very well covered and discussed on the interwebs! :-)