LINQ to SQL have 1:1 relation with each object having a property containing the other's id - linq-to-sql

I am wondering if there is any way in LINQ to SQL to have two tables point to one another's ids, such that there is a 1:1 relationship between them, and to create both of the objects with a single SubmitChanges.
For example, if I have one class Car, with properties CarExtension and CarExtensionID that point to a CarExtension object, and the CarExtension class in turn has Car and mandatory CarID properties that point back to the Car table, is there a way to set this up so that I can create a Car object, create a new CarExtension and assign it to the Car.CarExtension property, and then successfully submit changes?
Currently the SubmitChanges fails because LINQ to SQL doesn't know to assign the id of the newly created car to the .CarID property of the CarExtension, so then when it tries to create the CarExtension the creation fails since the required CarID field is blank.

Related

JPA JPQL - Query that returns if child object is not used (no primary key / foreign key relationship) and can be deleted

Spring Boot / MySQL / JPA / JPQL
I have an app that I would like to allow for the deletion of an object as long as it isn't being referend by another object (primary key / foreign key relationship)
For the UI I only want to show the delete button if there is no referential integrity issue/constraint (meaning if there is a pk/fk relation I don't want to show a delete button).
Let's say my child object is BookCategory and the parent object is Book. If a BookCategory is assigned to a Book then don't show the delete button, if there is no relationship then show the button.
Obviously in my case, BookCategory object model doesn't have a reference to Book, I could do that... but it seems a bit of resource waste, but maybe if I lazy load it wouldn't.
I'm trying to figure out a way through jpa / #query etc to allow for the UI to know whether to show the delete button or not.
I am looping through BookCategory(s) on the given page, but of course like I say it doesn't know if it is assigned to a book.
Seems like this thing would need to be done all the time, but not sure best how to build it.
Thanks, Keith
Suppose you have many to many connection between the entities.
In your example, you can use a lazy connection to the book and create an entity graph to load it when necessary or use jpql with join fetch.
You have to examine if there is a joined object or not, so you can also write a jpql to count the the joined object.
With Spring Data JPA you can create a composite model with, for example an id list, count... field refer to the books and put the other necessary fields for book category. Then spring data can load this into the model:
#Query(" select new com.mypackage.CustomBookCategory(b.name,count(b.book), ...) from BookCategory b where ...")
List<CustomBookCategory> findByCategory(String category);

Entity Framework 4.2 - How to realize TPT-Inheritance with Database-generated Primarykey Value?

I want to use the EF (4.2) in the following scenario:
There exists a database already (so I chose the database-first approach) and it is a SQL Anywhere DB.
I want to use persistence-ignorant business objects, so I use the DbContext Template to generate POCO classes from the EDM.
There is one simple inheritance hierarchy among my entities: an abstract base entity and two concrete derived entities.
In the database there is one table for each type of the inheritance hierarchy (Table-Per-Type Strategy).
Each of these three tables has a primary key column (Id, type:integer), and the association of a concrete entity to the base entity is done by having the same Id in both tables (that means that the primary key (Id) of the concrete type tables is at the same time a foreign key to the base table; a pretty common approach I think).
I had to define the Inheritance manually in the designer, since the EDM assistant does not automatically recognize, that is want to have an inheritance association between the described entities.
Until this point there wasn't any bigger problem. Now to the issue at hand:
There is a restriction for the database I use: Primarykey values have to be generated by the database, using a database function.
I want to call this function in a before-insert-trigger defined on the base-table.
To let the entity framework know that a value is generated by the database, I set the StoreGeneratedPattern property of the Id Property of the base-entity to Identity (As I understood, this is the way to tell EF to get the generated value after inserting a new instance of an entity).
When I create a new instance of a derived entity, add it to the corresponding DbSet of the DbContext and call SaveChanges on the context, a DbUpdateException is thrown, stating that a foreignkey constraint is violated.
By checking the request-log of the DB, I see that the base entity got inserted in the base table, but on inserting the row in the derived table, the above mentioned error occurs, because it obviously doesn't use the newly generated Id of the new entry in the base table.
Since I don't think there is much I can do on a database level against that, the question is, if the EDM or DbContext can be configured (or modified) to insert the base row first, then take the generated Id and use it for insertion of the derived row.
I know there are several way to avoid this situation (not using inheritance, using a stored procedure to insert a new derived entity, calling the id-generating db-function before inserting and set the Id property myself on the entity), but at the moment the above-described behavior would be the most preferable, so I want to make sure not to overlook something before deciding for any "plan B".
Any suggestions on this topic are much appreciated,
Thanks in advance.
Here is the code of the trigger:
ALTER TRIGGER "TRG_GENERATE_ID" before insert order 1 on
BASE_TABLE
referencing new as NewEntry
for each row
begin
declare NewID integer;
set NewID = F_GET_NEW_ID('BASE_TABLE', NewEntry.SOME_OTHER_ID);
set NewEntry.ID = NewID
end
The function "F_GET_NEW_ID" is called in the trigger to generate the new ID for a new entry in the base table. It has two parameters:
"Tablename" -> The name of the table for which a new ID should be generated,
and a second parameter that takes the value of a standardcolumn in all tables of the database (it is required to generate the new ID).

EF CodeFist Add rather than Update

I have two classes, one is Post and the other is Category, with a Many-to-Many relationship.
When i create a new Post business object, and a category object.
post.Categories.Add(category)
then using AutoMapper to map post from business model object to data entity,
when I do
dbContext.Posts.Add(post);
dbContext.SaveChanges();
it always add a new row to Categories table, even the category instance has value for ID, which is the key in database. Any one knows how to change this? if category info exists in database, then do nothing, except add a new row to CategpryPosts table
You need to attach the category to the context:
dbContext.Categories.Attach(category);
That tells EF it's an existing, unmodified entity.

Navigating by foreign keys in ADO.NET Entity Framework/MySQL

I am using ASP.NET MVC2 on top of a MySQL database in VS2008. I am using the MySQL ADO.NET connector 6.2.3 to provide the connection for the ADO.NET Entity Data Model.
This is mostly working ok, however navigating via foreign keys is causing me a real headache!
Here is a simplified example..
Car (Table)
CarID PK
Colour
Doors
ManufacturerID FK
Manufacturer (Table)
ManufacturerID PK
Name
In the edmx file I can see the 1-many relationship shown as a navigation property in the both the Car and Manufacturer tables. I create a Models.CarRepository that allows me to returns a IQueryable.
At the View I want to be able to display the Manufacturer.Name for each car. This is not accessible via the object I get returned.
What is best way to implement this? Have I encountered a limitation of the Entity Framework/MySQL combination?
Eager loading of the related records needs to be enabled in the Model Repository. Something like:
var allCars = from c in automobileEntites.Car.Include("Manufacturer")
select c;
This then makes the related records available for subsequent query/display.

When are LinqToSql Entity Id's assigned?

Are they assigned at SubmitChanges? or when a new object is created? If the latter, I would imagine there would be collisons?
If the id field is an autogenerated (identity/guid) field, the id is assigned when the record is inserted into the database. LINQToSQL does a select after insert to get the assigned value and updates it in the object. There are no collisions using identity columns as long as you don't turn on allow identity insert. If the id is not autogenerated, then you will be responsible for creating the id and ensuring that there aren't collisions.