Insert using NHibernate for n:n relationship - asp.net-mvc

I have Orders, Items and OrderItems entities with n:n relationship between Orders and Items table. I am using Fluent Hibernate for mapping, in "Order" entity there is "List" property which has "protective set". I am facing below problem, while inserting.
new Order.Items.Add(alreadyexistingitem);
Since its already existing item, in the orderitems table, a record needs to be inserted into orderitems table with new orderid and existing item id. But only new order details are inserted in order table not in associative table.
"Inverse" attribute is set for "items" bag in orders entity. So, I need to attach the newly added order while adding item like below but how can i do it as it is the list object with protective set.
Orders.Items.Add(alreadyexistingitem, *order = "neworder"*);
Below is the mapping:
model.Override<Order>(m =>
{
m.HasManyToMany(c => c.Items)
.Table(Constants.TABLE_PREFIX + "OrderItem")
.Inverse()
.Cascade.AllDeleteOrphan();
});
model.Override<Item>(m => m.HasManyToMany(c => c.Orders)
.Table(Constants.TABLE_PREFIX + "OrderItem")
.Cascade.None());

As a preliminary answer, NHibernate is smart enough to know when the same object reference is being used in two places. All you should need is a "HasManyToMany" relationship in the mapping between Order and Item.
Inverse should probably not be used on the orders side. Inverse tells NHibernate that the opposite side of the relationship has the power to define and break the relationship. Orders have items; items don't get to "choose" what order they belong to.

Related

Entity Framework many-to-many relation with filter in mapping

I'm trying to create a relation using Fluent API, but I can't get it to work. There are 2 tables: SecurityEntities and SecurityEntityRelations. The SecurityEntities table contains users and groups, the SecurityEntityRelation table is an association table that contains relations between the users and groups (it defines which groups contain which members). I already mamaged to relate the 2 entities within EntityTypeConfiguration:
HasMany(se => se.Groups).WithMany(g => g.Members).Map(seg =>
{
seg.MapLeftKey("ser_EntityName");
seg.MapRightKey("ser_MemberOf");
seg.ToTable("ser_SecurityEntityRelations");
});
This populates the SecurityEntity.Groups and Members properties. But one of the security groups is being concidered a "primary" group, which should be stored in a separate SecurityEntity.PrimaryGroup property. In SQL, this is implemented by a column in the SecurityEntityRelation table, which marks the relation as being "primary". (I know, a self-referencing foreign key in the SecurityEntity table would have been a better solution, but this was designed quite some time ago, and we're stuck with this implementation because our legacy code is also written this way) So, now my question is: how can I create an EF mapping like the one above, which specifies the same relation, but only when column "ser_IsPrimaryGroup" equals a fixed value of '1'?

Creating relationship in Core Data to perform deletion

I am new to core data just started learning the new ideas in core data.
I have core data database which has three entity Student,Department and an entity for Mapping Student and department.Let name it as StudentDepartment
Student will have all student details with a primary key studentID
Department will have department details with a primary key departmentID
StudentDepartment will have studentID and DepartmentID as foreign key.
Multiple student can be enrolled in a department and a same student can be enrolled to multiple department.
How to create this schema in core data.
If am deleting a studentID in student table subsequent row should be deleted in StudentDepartment table. Similarly if am deleting departmentID in department table subsequent rows should be deleted in StudentDepartment.How to make this relationship by using core data.
Please provide me a xcmodel.
CoreData isn't a database, it's an object store that happens to (sometimes) be implemented on top of a relational database.
The practical result of that is that you really don't need to explicitly create a separate table for relationship mapping. Instead you create your two entities and then create a relationship between the two. From your description, it sounds like you want a many-to-many relationship between the two. At an implementation level, core data will magically create the needed relationship table.
Additionally, you can establish a delete-rule for each side of the relationship that mandates what to do when an item is deleted. Pin this case, you'll want to set the delete rule for both to nullify, which will break the relationship when either end is deleted.

iOS Core Data "Views"

I have a bunch of entities in Core Data and I'm looking for a way to link them together into what I think is called a "View" in Sqlite for easy access.
For example...
Table 1: "Events"
EventId
VenueId
ArtistId
Table 2: "Venues"
VenueId
Name
City
Table 3: "Artists"
ArtistId
Name
Genre
Views: "MyEvents"
EventId
ArtistName
ArtistGenre
VenueName
VenueCity
isRegistered (property within table - doesn't fetch)
When I create a row to "MyEvents" with the EventId, it should fetch the data from the "Artist" table and the "Venue" table that correspond to that EventId.
Thoughts?
The word you are looking for is "Relationships".
Check out Apple's documentation or this tutorial.
Unfortunately there is no concept of a "View" in core data. There aren't really "Tables" either. Every records is an, "Entity" - which is essentially a Row in the "That Entity" table. And each "Entity" has attributes (Columns). Entities can have a "Relationship" (Foreign Key) based on their "Attributes" (Columns). When you perform a fetch a relationship behaves like a join.
To get the behavior you want you would have to add foreign keys or make add entities to relate your entities together: e.g. relate the "Events" and "Venues" entities by having an "EventVenueRelationship" entity with attributes "EventId" and "VenueId" and corresponding relationships.
I'm working on a similar problem at the moment where I have a db structure which is very federated and works great on the server, but is ridiculous when you try to shoehorn it into CD. Did you find a better way to solve this?

One to One error in Entity Framework 4

I have already read Entity Framework One-To-One Mapping Issues and this is not duplicate as the business rule specs are different here.
There are two tables, Invoices and Orders.
Invoices
-> InvoiceID (Primary, Auto Number)
Orders
-> OrderID (Primary, Auto Number)
-> InvoiceID (FK InvoiceID of Invoices Table)
Now the problem is, EF requires One to Many relationship for this association if names of properties are not same. If names of properties are same then it serves purpose of derived class, but here Order is not derived class or Invoice.
InvoiceID(s) are generated for every shopping cart, but OrderID(s) are only generated for paid invoices, so Every Order has InvoiceID but every Order does not have corresponding Invoice.
If I create a seperate table for this, then I have to write too much code to do it. Is there any way I can remove this restriction and let EF still process my model.
However, currently if I change the model as follow, it works
Invoices
-> InvoiceID (Primary, Auto Number)
Orders
-> OrderID (Auto Number)
-> InvoiceID (Primary, FK InvoiceID of Invoices Table)
But is this good practice? Because by definition InvoiceID of Orders table will certainly be unique, but we will be referring everywhere OrderID for comparison and lot of other references. I know I can index the property, but I dont feel this design is perfect.
What seems to be the obvious solution here is to change the 1:* association between Invoice
and Order in the EDM into a 1:1 association. However, as you experienced, the mapping will not
validate when you have a Foreign Key Association between the two entities as in your model.
The only way to map a unique foreign key association is by using an Independent Association. This is the same type of association that we had in EF3.5, where foreign keys were not supported.
To turn the foreign key association into an independent association would mean removing the InvoiceID foreign key from the Order entity and recreating the association through mappings.
To make the change to the association, you’ll need to do the following:
Delete the InvoiceID foreign key property from Order entity.
Select the Asscoation between Invoice and Order.
In the Properties window for the association, open the Referential Constraints by
clicking the ellipses next to that property.
Delete the constraint by clicking the Delete button.
Right-click the association in the Designer and select Table Mapping from the context menu.
In the Mapping Details window, click the element to expose the drop-down.
From the drop-down, select Order. The mappings should populate automatically.
Return to the Properties window for the association.
For the property called “End2 Multiplicity,” which currently has the value * Collection of Orders, change that property to 1 (One of Order) using its drop-down list.
Validate the model by right-clicking the design surface and choosing Validate. You will see that the error message related to this mapping is gone.
When encountering this problem in your application, you’ll have to decide which is more important to your model and your application logic: the foreign key scalar (e.g., Order.InvoiceID) or being able to define a 1:1 association between one entity (Invoice) and another (Order) when they are joined through a foreign key (InvoiceID).
The good news is that the new EF4.0 Lazy Loading will be still working with Independent Associations, just the Foreign key is not exposed. To get that you would have to go over to the navigation property (Invoice) and read its InvoiceID like the code below:
Order order = context.Orders.First();
int invoiceID = order.Invoice.InvoiceID;
Or you can use the code below to read it right on the Order entity withought having to Lazy Load or Eager Load the Invoice property:
int invoiceID = order.InvoiceReference.EntityKey.EntityKeyValues[0].Value;

How to layout tables and relationships for MVC project

So I am working on an MVC project to put to work the studying I have been doing. I am wrestling with the concept of Database Table relationships and foreign keys. I am working on a simple ecommerce site (displays products, shopping cart, user accounts..etc).
I have the following tables to start out with:
1) Products
2) Categories
I setup the Products and Categories tables to have a ProductId and CategoryId respectively. In my MySQL db, I created a FK on the Products Table to relate to the CategoryId field on the Categories table (I am not sure this was correct to begin).
My expectations for the way the database would handle the table relationship: I didn't want the DB to do anything with the products table if I deleted a category out of the Categories table, or vise versa. The only thing would be that the category field in a Product would be blank (or default) if their category was removed.
Finally, do I have to do anything in my entity classes such as in the Products class, add the ProductId to the Category.ProductId?
Eventually, when I Orders and Users to the project, I can see a relationship where each user -> many orders -> each order has many products -> and each product is in one category.
But I am having a hard time understanding how or if I should be setting up a Foreign key relationship in the two current tables of Products and Categories and if so how to setup my entity class in relation to that FK.
Any advice.
It has been my experience (with L2S) that you don't want to specify any relationships between tables. I have simply done the PK, FK logic myself. This keeps the L2S generated objects simple and is most likely the way you worked with them before in SQL. That, at least, is the case for me.

Resources