Error in MySQL syntax when adding object to objectcontext - c#

I seem to have trouble adding objects to tables that have a 'n to n' relationship.
Tables are defined as follows:
Table A
ID (PRIMARY)
...
...
...
Table B
ID (PRIMARY)
...
...
...
Table C
TableA_ID (index)
TableB_ID (index)
So basically Table C links Table A and B, by their IDs. Using the entity framework we now have an object TableA containing an Entity Collection of TableB entities.
However when I add an existing object of type TableB to the TableA.TableBs entity collection property, I receive an exception:
You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near '(SELECT\n TableC.TableA, \n ' at line 1
It seems that I'm trying to do a very normal / common thing, however I've not been successful getting this to work.
C# code:
var database = new DatabaseEntities();
var tableAObject = database.SingleOrDefault(e => e.ID == 1);
var tableBObject = database.SingleOrDefault(e => e.ID == 1);
tableA.TableBEntities.Add(tableBObject);
database.SaveChanges();
Apparently I'm doing something wrong, so my question is, how should I add an object to Table C?

Related

Get values of foreign keys tables linked in c#

I have a question about foreign keys in a database. I am programming in c#, using the Entity framework (visual studio winforms) and I have data in my sql database with foreign keys.
I have queries which access these data to get them in a Datagrid. Everything is OK, except I have data in tables which are foreign keys (numbers). When I select them with queries I only get the foreign key (a number) and not the value which is linked in another table.
var requete_reservations = from reservation_spa in bdd.reservation_spa
where reservation_spa.NOMBRE_RESERVATION > 0
select new
{
reservation_spa.CLIENT,
reservation_spa.SPA,
reservation_spa.NOMBRE_RESERVATION
};
dataGrid_reservations.DataSource = requete_reservations.ToList();
In reservation_spa.client I have a number which links another table client
How can I get the Name from client using the foreign keys in reservation_spa?
You must Join table reservation_spa and Client like this :
var requete_reservations = from r in bdd.reservation_spa
join c in bdd.client on r.CLIENT equals c.IDCLIENT
where r.NOMBRE_RESERVATION > 0
select new
{
c.NOM,
r.SPA,
r.NOMBRE_RESERVATION
};
Where is the name for? If you just need the name you could use linq
var name= from c in bdd.Clients //Is that the name of the table of clients?
where c.IDClient= requete_reservations.Client
select c;

NHibernate executing a SELECT before every INSERT

I have an entity with only one field (Value) and the following mapping:
Id(x => x.Value).Column("value").Length(150);
When I execute the following code
using (var tx = Database.BeginTransaction())
{
for (int i = 0; i < 10; i++)
{
var e = new Entity { Id = "Value" + i };
Database.Entities.Add(e);
}
tx.Commit();
}
NHibernate executes a SELECT statement before each INSERT call. Something like this:
NHibernate: SELECT * FROM entity entity_ WHERE entity_.value=#p0; #p0 = 'Value0'
NHibernate: INSERT INTO entity ...
NHibernate: SELECT * FROM entity entity_ WHERE entity_.value=#p0; #p0 = 'Value1'
NHibernate: INSERT INTO entity ...
NHibernate: SELECT * FROM entity entity_ WHERE entity_.value=#p0; #p0 = 'Value2'
NHibernate: INSERT INTO entity ...
If I enable the bulk mode (setting adonet.batch_size) it executes all the SELECT statements first and then the INSERT ones in bulk mode.
Is that the intended behavior? If so, what should I do to avoid that?
This behaviour is correct, related to these facts:
The ID beeing string -> has generator type assigned (the fluent-mapping line in a question)
While discouraged, the session.SaveOrUpdate(e) was used
See: 5.1.4.7. Assigned Identifiers, Extract:
Due to its inherent nature, entities that use this generator cannot be
saved via the ISession's SaveOrUpdate() method. Instead you have to
explicitly specify to NHibernate if the object should be saved or
updated by calling either the Save() or Update() method of the
ISession.
In this case, NHibernate is almost desperate. Why? Because there is no way how to assure, that the assigned id ('value1', 'value2'..) is already in DB or not. So, to be sure if the INSERT or UPDATE should be issued, it must ask the DB. That's why the SELECT before that decision.
Use the Save(e) only, behind the Database.Entities.Add(e) and no supporting infrastructural SELECT will be issued.

Entity Framework is slow because of derived tables

I am using MySQL Connector/Net 6.5.4 with LINQ to entities, and I frequently get terrible query performance because the entity framework generates queries that use derived tables.
Here is a simplified example of what I've encountered several times. In C#, I write a query like this:
var culverCustomers = from cs in db.CustomerSummaries where cs.Street == "Culver" select cs;
// later...
var sortedCustomers = culverCustomers.OrderBy(cs => cs.Name).ToList();
Instead of generating simple a query like this:
SELECT cust.id FROM customer_summary cust WHERE cust.street = "Culver" ORDER BY cust.name
The entity framework generates a query with a derived table like this:
SELECT Project1.id FROM (
SELECT cust.id, cust.name, cust.street FROM customer_summary cust
WHERE Project1.street = "Culver"
) AS Project1 -- here is where the EF generates a pointless derived table
ORDER BY Project1.name
If I explain both queries I get this for the first query:
id, select_type, table, type, possible_keys, rows
1, PRIMARY, addr, ALL, PRIMARY, 9
1, PRIMARY, cust, ref, PRIMARY, 4
... and something awful like this for the entity framework query
id, select_type, table, type, possible_keys, rows
1, PRIMARY, <derived2>, ALL, 9639
2, DERIVED, addr, ALL, PRIMARY, 9
2, DERIVED, cust, ref, PRIMARY, 4
Note the first row, where MySQL explains that it's scanning 9000+ records. Because of the derived table, MySQL is creating a temp table and loading every row. (Or so I'm deducing based on articles like this one: Derived Tables and Views Performance)
How can I prevent the Entity Framework from using a derived table, or how can I convince MySQL to do the obvious optimization for queries like this?
For completion, here is the view that is the source for this linq query:
create view customer_summary as
select cust.id, cust.name, addr.street
customers cust
join addresses addr
on addr.customer_id = cust.id
I think your query statement is missing 'select'. You have not identified the record(s) you want.
your query:
var culverCustomers = from cs in db.CustomerSummaries
where cs.Street == "Culver";
//no select
what are you selecting from the table? try this
example:
var culverCustomers = from cs in db.CustomerSummaries
where cs.Street == "Culver"
select cs;

Load foreign key value with linq to entities

I have a table Admins, which creates a relationship between Users and Locations:
ID - numeric (PK)
UserId - uniqueidentifier (FK to UserId in aspnet_Users table)
LocationId - numeric
Now I want to execute command:
IQueryable<decimal> location_ids = (from m in _db.Admins
where m.UserId.Equals( new Guid("c5d3dc0e-81e6-4d6b-a9c3-faa802e10b7d")) && m.LocationId.Equals(conf.umisteni.Budova.ID)
select m.LocationId);
But for some reason (I guess the UsersId is FK) m.UserId can't be resolved. So I tried to use
m.aspnet_UsersReference.Value.UserId
But then the decision statement
if (!location_ids.Any())
fails with exception
System.NotSupportedException: The specified type member 'aspnet_UsersReference' is not supported in LINQ to Entities. Only initializers, entity members, and entity navigation properties are supported.
What should I do in order to get the enumerable list of LocationIds?
Thanks in advance.
You're missing a 'Users' and a dot:
var location_ids = (from m in _db.Admins
where m.Users.UserId.Equals(
new Guid("c5d3dc0e-81e6-4d6b-a9c3-faa802e10b7d")) &&
m.LocationId.Equals(conf.umisteni.Budova.ID)
select m.LocationId);
Essentially, you need to use the relationship "Users" directly.

linq to entities inheritance query problem

I'm trying to perform a linq to entities query on a table that's inherited using Table per Type.
The problem I'm having is that I can't get at the properties on the Inhertied table only the properties on the Base Table.
var qry = from i in _DB.BaseTable
where i is catalogueModel.InheritedTable
// Field Doesn't Exist
// && i.InheritedTableField == "Value"
select i;
When I try to cast the Inherited Table to it's type...
var qry = from i in _DB.BaseTable
where i is catalogueModel.InheritedTable
&& (i as catalogueModel.InheritedTable).InheritedTableField == "Value"
select i;
...the code compiles but i get a cool error which reads
Only text pointers are allowed in work
tables, never text, ntext, or image
columns. The query processor produced
a query plan that required a text,
ntext, or image column in a work
table.
I suppose my question is How are you supposed to access the properties of the Inherited tables in linq to entities when using Table per Type?
Use .OfType():
var qry = from i in _DB.BaseTable.OfType<InheritedTable>()
select i.InheritedTableField;
You can also use IS
var qry = from i in _DB.BaseTable where i is InheritedTable select i.InheritedTableField;
Here are a few others to help (using Entity SQL)
var q = SELECT VALUE c FROM OFTYPE(yourcontext.yourbaseclass, yourmodel.yoursubclass) AS c
var q = SELECT VALUE c FROM yourcontext.yourbaseclass AS c where c IS NOT OF (yourmodel.yoursubclass)

Categories