Store Object in database which have array of objects - object-oriented-database

How can we store object in database which have array of object inside it.
For ex.
Class Foo {
public List<object> Bar = new List<object>();
}
Can give answer in php or c#.

One thing you could do is have table Foo, table Bar, and table FooBar. Foo and FooBar would have some sort of unique identifier with them, and FooBar would have the map. The query you could execute is
SELECT Foo.Id AS FooId, Bar.Id AS BarId, Bar.Column1, Bar.Column2
FROM Foo
INNER JOIN FooBar
ON Foo.Id = FooBar.FooId
INNER JOIN Bar
ON FooBar.BarId = Bar.Id
Note that I'm no DBA or SQL expert, so there may be a better way of doing this.

Related

Load subentities with JPQL/EntitGraph is not working with EclipseLink and spring data

I'm trying to use EntityGraphs or JPQL to create 1 select instead of many small (sub) selects. However, there sub entities are loaded in extra selects.
Example:
#NamedEntityGraph( name = "All",
attributeNodes = {
#NamedAttributeNode( value = "bars", subgraph = "subgraph.foobars") },
subgraphs = {
#NamedSubgraph( name = "subgraph.foobars",
attributeNodes = {
#NamedAttributeNode(value = "fooBars", subgraph = "subgraph.foobar"),
#NamedAttributeNode( "mqttEndpoints" ) } ),
#NamedSubgraph( name = "subgraph.foobar",
attributeNodes = {
#NamedAttributeNode( "name" ) } ) })
public class Foo {
#OneToMany( fetch = FetchType.LAZY )
private Set<Bar> bars = Sets.newHashSet();
}
public class Bar {
#OneToMany( fetch = FetchType.LAZY )
private Set<FooBar> fooBars = Sets.newHashSet();
}
public class FooBar {
String name;
}
#EntityGraph( value = "All", type = EntityGraph.EntityGraphType.FETCH )
Optional<Foo> findById( String id);
#Query( "SELECT DISTINCT f FROM foo f"
+ " LEFT JOIN FETCH f.bar bars "
+ " LEFT JOIN FETCH bar.fooBars foobars "
+ " WHERE t.id =:id " )
Optional<Foo> readById( String id);
Log
SELECT ...
FROM foo t1
LEFT OUTER JOIN bars t0 ON (t0.bar_id = t1.id)
SELECT name
FROM foobar
WHERE ...
If i use queryhints then it works with subselect so what is wrong?
https://www.eclipse.org/eclipselink/documentation/2.5/jpa/extensions/q_left-join-fetch.htm
With hibernate this works well.
EclipseLink you'll notice always does an extra query for any relationship mapping unless you specify a fetchJoin annotation (or query hint, or modify the mapping with customizers) that tells it what to do, and this is independent of the relationship being eager or lazily fetched. Hibernate on the other hand interprets all eager access to use join. No point debating which is better - they are situational and there are good reasons to go with either solution as a generic one.
This means that if you want a join with EclipseLink on the fly, you'll have to do more than just indicate the relationship needs to be eagerly fetched, and include in query hints. If you are going with fetch graphs to optimize things, it might be a helpful to look into the other fetch types, such as batch fetching. An extra query/statement isn't always a bad thing for performance, especially as object graphs grow. The database is going to be forced to return N*M duplicate rows of Foo data, one for each Bar and FooBar combination in the results. Depending on the data size, there will be a point where it is more efficient to get the children in separate queries.

LINQ to Entities does not recognize the method with Let Statement

I am in the process of converting an application that uses LINQ to SQL over to LINQ to Entities. I use a repository pattern and I have run in a problem that works in LINQ to SQL but not Entities.
In my data layer, I use LINQ statements to fill my object graph so that none of my database entities are exposed anywhere else. In this example, I have a Lookup Respository that returns a list of Categories. It looks like this:
public IQueryable<Entities.DomainModels.Category> getCategories()
{
return (from c in Categories
where !c.inactive
orderby c.categoryName
select new Entities.DomainModels.Category
{
id = c.categoryID,
category = c.categoryName,
inactive = c.inactive
});
}
Later, I want to put the categories into a sub query and it looks like this:
var d = from p in Programs
let categories = (from pc in p.Categories
join c in getCategories() on pc.categoryID equals c.id
select c)
select new
{
id = p.id,
title = p.title
categories = categories.ToList()
};
When I run this, I get the following error:
LINQ to Entities does not recognize the method 'System.Linq.IQueryable`1[Entities.DomainModels.Category] getCategories()' method, and this method cannot be translated into a store expression.
For reference, the following works though it doesn't return the data I need (it's basically a join):
var q = from p in Programs
from pc in p.Categories
join c in getCategories() on pc.categoryID equals c.id
select new
{
id = p.id,
category = c
};
I understand what the error means in concept however LINQ to SQL would make it work. I have this pattern throughout my data layer and I really want to keep it. Should this be working? If not, how can I modify it without mixing my layers.
You cant pass getCategories() to EF.
The query must be destructible to expression tree.
Calculate getCategories() first.
eg
var simpleList = getCategories().Select(id).Tolist;
then use a contains
where(t=> simpleList.Contains(t.CatId) // or the query syntax equivalent

Entity Framework: selecting from multiple tables

I have a statement:
var items = from e in db.Elements
join a in db.LookUp
on e.ID equals a.ElementID
where e.Something == something
select new Element
{
ID = e.ID,
LookUpID = a.ID
// some other data get populated here as well
};
As you can see, all I need is a collection of Element objects with data from both tables - Elements and LookUp. This works fine. But then I need to know the number of elements selected:
int count = items.Count();
... this call throws System.NotSupportedException:
"The entity or complex type 'Database.Element' cannot be constructed in a LINQ to Entities query."
How am I supposed to select values from multiple tables into one object in Entity Framework? Thanks for any help!
You are not allowed to create an Entity class in your projection, you have to either project to a new class or an anonymous type
select new
{
ID = e.ID,
LookUpID = a.ID
// some other data get populated here as well
};
Your code doesn't work at all. The part you think worked has never been executed. The first time you executed it was when you called Count.
As exception says you cannot construct mapped entity in projection. Projection can be made only to anonymous or non mapped types. Also it is not clear why you even need this. If your class is correctly mapped you should simply call:
var items = from e in db.Elements
where e.Something == something
select e;
If LookupID is mapped property of your Element class it will be filled. If it is not mapped property you will not be able to load it with single query to Element.

Order Zend_Db_Table rowset by reference column

i know i can define relationships through _referenceMap, i know that i con join selects trough
$db->select()
But what i need is to fetch rowset in model extending Zend_Db_Table_Abstract and then order it by value of referenced column from another table.
Is there some workaround to do that?
edit:
heres is the example:
first table:
table bugs columns id, bugname, authorid
second table:
table authors columns id, authorname
I have a model Model_Bugs extends Zend_Db_Table_Abstract
I want to make something like this:
$model->fetchAll($model->select()->order('authorname ASC'))
This means, that i need to join tables and sort by a column, which is not in the model table.
thanks for help
Jan
I would add a method in Model_Bugs like so:
public function fetchBugsByAuthorname() {
$bugTable = $this;
$bugTableName = $this->info('name');
$authorsTable = new Model_Authors();
$authorsTableName = $authorsTable->info('name');
$select = $bugTable->select()
->setIntegrityCheck(false)
->from($bugTable, array('id', 'bugname', 'authorid'))
->join($authorsTableName,
"$bugTableName.authorid = $authorsTableName.id",
array("authorname"))
->order("$authorsTableName.authorname asc");
$result = $bugTable->fetchAll($select);
return $result;
}
But to do this you have to turn off ZF's table integrity checking (setIntegrityCheck(false) above), which means you won't be able to directly call save() on the resulting rows. But if it's for a read-only purpose, it will work.
If you needed to save rowsets back to the database, you may have to first select the author ID's from Model_Authors in the order you want them, and then re-order your Model_Bugs query accordingly. It's messier but it can work.

Fetch only key value from EF association

I've set up a many-to-many association between two tables based on a third table that just holds a pair of key values. Now I'd like to do a query that groups the right tables key values by the lefts without needing other data.
LeftTable { LeftID, LeftField1, LeftField2 }
JoinTable { LeftID, RightID}
RightTable { RightID, RightField1, RightField2 }
Is there any way to essentially just query the JoinTable and get all the 'RightIDs' grouped by the 'LeftIDs' without the SQL trying to fetch the fields from either side?
The JoinTable is not an entity in its own right in the model, but is mapped to the association.
I've experimented a bit with both using ObjectQuery and EntityCommand (ESQL) and both seem to still load in the other fields by joining to RightTable which I don't need.
My ESQL looks something like:
SELECT lt.LeftID, (SELECT rt.RightID
FROM NAVIGATE(lt, MyModel.LeftToRightAssoc, RightTable) as rt)
FROM MyEntities.LeftTable as lt;
but the generated SQL is still fetching in RightField1 and RightField2.
Surely there must be a simpler way to do this?
Assuming that your class Left has a navigation property Rights (a collection of Right entities) you could try this:
var list = context.Lefts.Select(l => new
{
LeftId = l.LeftId,
RightIds = l.Rights.Select(r => r.RightId)
});
foreach (var item in list)
{
Console.WriteLine("LeftId = {0}", item.LeftId);
foreach (var rightId in item.RightIds)
{
Console.WriteLine("RightId = {0}", rightId);
}
}
You would get a collection of anonymous type objects where each element has the LeftId and a collection of corresponding RightIds. This query should not touch the other fields like RightField1, etc. Instead of an anonymous type you could also create your own custom type and then project into this type in the query above.