Can you write to an Entity Framework database using plain SQL - asp.net

Can someone help me answer these questions on EntityFramework?
Does it do anything special to the database? (like extra tables)
Can I add data directly with SQL without breaking EF?
Can I add tables and fields without breaking EF?

Yes you can access database with plain SQL when using EF.
No. EF just uses database. There is one exception in code first approach where EF can create one additional table for its own purpose called EdmMetadata.
Yes you can add data directly with SQL. If both your entity model and database are defined correctly it will not break EF.
Yes you can add new tables directly but EF will not know about them. You should not change existing tables because it can break EF.

You can do it with:
var context = new YourObjectContext();
var s = context.ExecuteStoreCommand("some query");
if your query create a table, this only create a table on db and not effected on EF

Related

Efficient way to load lists of objects from database to instantiate a single object

My situation
I have a c# object which contains some lists. One of these lists are for example a list of tags, which is a list of c# "SystemTag"-objects. I want to instantiate this object the most efficient way.
In my database structure, I have the following tables:
dbObject - the table which contains some basic information about my c# object
dbTags - a list of all available tabs
dbTagConnections - a list which has 2 fields: TagID and ObjectID (to make sure an object can have several tags)
(I have several other similar types of data)
This is how I do it now...
Retrieve my object from the DB using an ID
Send the DB object to a "Object factory" pattern, which then realise we have to get the tags (and other lists). Then it sends a call to the DAL layer using the ID of our C# object
The DAL layer retrieves the data from the DB
These data are send to a "TagFactory" pattern which converts to tags
We are back to the Object Factory
This is really inefficient and we have many calls to the database. This especially gives problems as I have 4+ types of lists.
What have I tried?
I am not really good at SQL, but I've tried the following query:
SELECT * FROM dbObject p
LEFT JOIN dbTagConnection c on p.Id= c.PointId
LEFT JOIN dbTags t on c.TagId = t.dbTagId
WHERE ....
However, this retreives as many objects as there are tagconnections - so I don't see joins as a good way to do this.
Other info...
Using .NET Framework 4.0
Using LINQ to SQL (BLL and DAL layer with Factory patterns in the BLL to convert from DAL objects)
...
So - how do I solve this as efficient as possible? :-) Thanks!
At first sight I don't see your current way of work as "inefficient" (with the information provided). I would replace the code:
SELECT * FROM dbObject p
LEFT JOIN dbTagConnection c on p.Id= c.PointId
LEFT JOIN dbTags t on c.TagId = t.dbTagId
WHERE ...
by two calls to the DALs methods, first to retrieve the object main data (1) and one after that to get, only, the data of the tags related (2) so that your factory can fill-up the object's tags list:
(1)
SELECT * FROM dbObject WHERE Id=#objectId
(2)
SELECT t.* FROM dbTags t
INNER JOIN dbTag Connection c ON c.TagId = t.dbTagId
INNER JOIN dbObject p ON p.Id = c.PointId
WHERE p.Id=#objectId
If you have many objects and the amount of data is just a few (meaning that your are not going to manage big volumes) then I would look for a ORM based solution as the Entity Framework.
I (still) feel comfortable writing SQL queries in the DAOs to have under control all queries being sent to the DB server, but finally it is because in our situation is a need. I don't see any inconvenience on having to query the database to recover, first, the object data (SELECT * FROM dbObject WHERE ID=#myId) and fill the object instance, and then query again the DB to recover all satellite data that you may need (the Tags in your case).
You have be more concise about your scenario so that we can provide valuable recommendations for your particular scenario. Hope this is useful you you anyway.
We used stored procedures that returned multiple resultsets, in a similar situation in a previous project using Java/MSSQL server/Plain JDBC.
The stored procedure takes the ID corresponding to the object to be retrieved, return the row to build the primary object, followed by multiple records of each one-to-many relationship with the primary object. This allowed us to build the object in its entirety in a single database interaction.
Have you thought about using the entity framework? You would then interact with your database in the same way as you would interact with any other type of class in your application.
It's really simple to set up and you would create the relationships between your database tables in the entity designer - this will give you all the foreign keys you need to call related objects. If you have all your keys set up in the database then the entity designer will use these instead - creating all the objects is as simple as selecting 'Create model from database' and when you make changes to your database you simply right-click in your designer and choose 'update model from database'
The framework takes care of all the SQL for you - so you don't need to worry about that; in most cases..
A great starting place to get up and running with this would be here, and here
Once you have it all set up you can use LINQ to easily query the database.
You will find this a lot more efficient than going down the table adapter route (assuming that's what you're doing at the moment?)
Sorry if i missed something and you're already using this.. :)
As far I guess, your database exists already and you are familiar enough with SQL.
You might want to use a Micro ORM, like petapoco.
To use it, you have to write classes that matches the tables you have in the database (there are T4 generator to do this automatically with Visual Studio 2010), then you can write wrappers to create richer business objects (you can use the ValueInjecter to do it, it is the simpler I ever used), or you can use them as they are.
Petapoco handles insert / update operations, and it retrieves generated IDs automatically.
Because Petapoco handles multiple relationships too, it seems to fit your requirements.

Knowing web sql database is already created or not

Is there any way to know wheather new database is created or connected to existing one, when calling window.openDatabase() ? I think i have to create tables only when newly created.
Don't worry about the openDatabase() command. Instead modify your SQL so it only creates the tables if they don't exist like so:
CREATE TABLE IF NOT EXISTS DEMO (id unique, data)

DynamicData - Dynamic Linq Classes

Anybody know if it's possible to;
Dynamically create LINQ classes for tables/columns that change regularly?
If that creation can be used in DynamicData.
A web app we are developing creates tables and columns in SQL. We want to edit these tables in DynamicData.
Thoughts?
Depending on what type of Database you are running, but you could always have a linq statement that queries the systems schema table and have it return the tables and columns. Then could use what you return and then use another linq query to break out the information from each table.
I used sqlmetal.exe from the SDK, it's a winner.

Asp.net MVC3 with LINQ to SQL on multiple identical tables

I successfully retrieved data from an already populated table of a live database using mvc3 and linq 2 SQL. The table is defined in the DataClasses1.dbml.
Now I have to retrieve data from other tables with the same identical structure of DataClasses1 but from different databases on the same SQL Server( DB1.Customers DB2.Customers ecc), and display them grouped by database name.
1) How can I do that without creating N DataClassesN.dbml ? I guess since it's the same table structure I can avoid doing it.
2) (Optional): How can I automatically retrieve data also from tables of new created databases?
3) (Not relevant): How can I define a strongly type view? Seems I can do it using EF but I cannot do it using LINQ 2 SQL.
I already thought of creating a view on the database with all the customers tables, but it seems it's a too heavy view!
I have a query that returns all the database names (Select name from master..syttables), is it useful?
Thanks in advance
You just pass a different connection string to the data context when you create it. If the databases are truly identical, including all the foreign key relationships, then just do something like:
var dc = new DataClasses1(db1connectionstring);
// Do your display of database 1 data
var dc2 = new DataClasses1(db2connectionstring);
// Do your display of database 2 data
I have no idea what you mean by #2. Data doesn't retrieve itself.
You can't obviously join results from 2 databases in SQL so you'd probably have to use 2 queries (one to each database) with one of them selecting into a new Entity of the other database and then join the results in memory using LINQ afterwards. So one query returns DB1.EntityName and the other returns DB2.EntityName but with a select mapping this to new DB1.EntityName entities and then join the two. It's not a pretty solution but is the best I can think of off the top of my head.
If you just want each database to have a set of results each then obvioulsy you can just return 2 result sets. Let me know if I misunderstood your question.

how to add a new table using EFCodeFirst to the existing database aspnetdb.mdf?

I have not found information how to do the following:
how to add a new table using EFCodeFirst to the existing database aspnetdb.mdf?
Seems EFCodeFirst CTP5 is only able to create databases from scratch, and not generate tables in existing ones. :/

Resources