EF CORE loads all data before any query takes place - entity-framework-core

I have a console app to test EF Core with SQL Server Express edition. I have the following code in Program.cs
using EFCoreTutorials;
using EFCoreTutorials.Entities;
using Microsoft.EntityFrameworkCore;
using (var context = new SalesManagementContext())
{
var employees = context.Employees.ToList();
}
I wonder why context.Employees brings all data from my employees table without even asking for it with a query. If I have many tables in my database and my context class with a lot of data , are all these available from the context var at the beginning of program without even specifying which one of these I actuall want to use?
Thank you

Related

Raw SQL with Entity Framework

I am trying to write a simple raw query with Entity Framework to my database:
[ResponseType(typeof(Customer))]
[Route("name/{name}")]
[HttpGet]
public List<Customer> GetCustomerName(string name)
{
//var results = db.Customers.SqlQuery("SELECT Name from dbo.Customer").Where(p => p.Name.Equals(name)).ToList();
var results = db.Customers.SqlQuery("SELECT Name from dbo.Customer WHERE Name = #Name",new SqlParameter("#Name",name)).ToList();
//var results = db.Customers.Where(p => p.Name.Equals(name));
return results;
}
The last Entity Framework query works just fine, but I want to do raw SQL to get something back simple because I have never gotten raw SQL with Entity Framework to work and I see all of these examples where people says it works for them. The top 2 var results do not work I get this error any help would be greatly appreciated. I am a Web API 2 newbie and I am just trying to learn it
So the error says a member of the type AccrRevAcct does not have a corresponding column. I am not sure what that means AccrRevAcct is a column on my database but so is Name and I just want the Name of my customer.
http://localhost:61280/api/Customers/name/1st MIDAMERICA CREDIT UNION
This is the call I make to my server and like I said it returns fine with the 3rd statement but that isn't raw SQL like I want to achieve. I only want to do this because I have some developers saying they can't get everything to work in EF I personally like it and haven't ran into this problem I want to show them fine just drop to raw SQL, but I need to show them I can make it work first lol.
If you are using SqlQuery on the DbSet you have to return a full instance. If you want to reshape the data like you are doing you need to use the SqlQuery<T> on the db.Database instead.
Example from https://msdn.microsoft.com/en-us/library/jj592907(v=vs.113).aspx
using (var context = new BloggingContext())
{
var blogNames = context.Database.SqlQuery<string>(
"SELECT Name FROM dbo.Blogs").ToList();
}
Honestly I think you are trying to solve the wrong problem. The last query is the one you should be using. If your developers can't get EF to work that is what needs to be fixed.

How to use EF core owned entites

I am using a SQLite database EFCore 2.0 preview in UWP Project.
The address table is split into to different entities
Delivery address,
Invoice Address
using
modelBuilder.Entity<Project>().OwnsOne(p => p.DeliveryAddress);
which works great for setting up the database, with migrations, creates the different table in the database. With test data that I have put in manually works great at reading data from these tables. But how do I save changes to the DeliveryAddress table. Nothing is getting persisted to the database, when I save the using:
public void UpdateDeliveryAddress(Project modifiedProject)
{
using (var db = new SteelFrameCalculatorDataContext())
{
db.Entry(modifiedProject).State = EntityState.Modified;
db.SaveChanges();
}
}
Project being the parent entity
2017-06-11T23:21:10.9242463+01:00 Warning 8 Microsoft.EntityFrameworkCore.Model.Validation
The key {'ProjectId'} on entity type 'Project.DeliveryAddress->Address' contains properties in shadow state - {'ProjectId'}. To configure this warning use the DbContextOptionsBuilder.ConfigureWarnings API (event id 'CoreEventId.ModelValidationShadowKeyWarning'). ConfigureWarnings can be used when overriding the DbContext.OnConfiguring method or using AddDbContext on the application service provider.
Using the following allowed in to save updates to the database. Assume the UpdateRange(entity) sets all to modified. Not sure if this is the correct way, but it works.
using (var db = new SteelFrameCalculatorDataContext())
{
db.UpdateRange(modifiedProject);
db.SaveChanges();
}
Have you tried setting the state of the child object? Looks like you're only setting the parent Project state.
Adding this should do it:
db.Entry(modifiedProject.DeliveryAddress).State = EntityState.Modified;
db.Entry(modifiedProject).Reference(a=>a.DeliveryAddress).TargetEntry.State = EntityState.Modified;

Entity Framework Core - Get DbContext data model

I need to know information about entities, tables, mappings, keys etc for the given instance of DbContext. In Entity Framework 6 I was writing edmx like this:
System.Data.Entity.Infrastructure.EdmxWriter.WriteEdmx(dbContext, xmlWriter);
which I then used to build my own data model (this is needed for a tool which supports loading data from different sources). How do I get such information for the new EF Core (previous EF 7)? I could use Reflection, but this will give me only the conceptual schema, while I also need mappings and storage schema. I've been looking through the EF source code for a while now, but don't seem to find any object, that stores all the required data.
This should get you started
using (var ctx = new TestContext())
{
var entityType = ctx.Model.FindEntityType(typeof (Entity_Basic));
var tableName = entityType.SqlServer().TableName;
var columnName = entityType.GetProperties().ToList()[0].SqlServer().ColumnName;
}

Model is not reading from my Database (Entitity Framework)

I created simple MVC application with a database.
First I created a database, initialized the database, then I created a model from the database and the application worked..
Then I decide to load database with totaly different values (but the definitons of tables/fields stayed the same)..
After reloading the database my application does not shows any data from my DB. Using debugger I saw that my application cannot get any data from the table.
Worse - I noticed that additional to my database TestDB, the database explorer is showing TestDB.mdf1 database, with the same definitions as testDB.mdf but table is empty...
Here is the code:
public ActionResult ShowQuestions()
{
TestDBEntities _db = new TestDBEntities(); // this is the database
ObjectSet<question> all_quest = _db.questions ; // this is the table
foreach (var x in all_quest)
{
..... // this part was never executed
}
return View(q_list);
}
Any ideas what I am doing wrong?
1- check the connection string in your MVC application (web.config). This will tell you which database is being used. Then go to this database and check if you have data in your tables.
If it's the wrong database, just amend the connection string.
2- If it's the correct database, but without data, just add data.
It may have been recreated by your ORM (who knows?).
3- What is the error you are getting? Or are you getting any error?

Trying to traverse tables from sql database using entity framework targeting .net 3.5 websites

I'm simply trying to get data from two sql server db tables using ado.net entity framework. My code is:
using (Model.Entities e = new Model.Entities())
{
return e.PAGE.First().CONTROL;
}
The database is setup to have two tables, a control table which links to a page table via an 'id' field in the tables (control_id). There is one CONTROL object for each PAGE object.
I keep getting a null value for my return value and I know that's not right.
I can use vis studio and breakpoints to see that there is a PAGE object in 'e' and I can see that there are multiple CONTROL objects in 'e'. This isn't a large database, I just have some sample data in there to ensure that I get this working - so I know that there should be a CONTROL object connected to this PAGE (i've verified this through sql server).
I am very familiar with the general code syntax, I've been using LINQ for a couple of years; however, I have not done much work at all with the entity framework or ado.net 4.
It seems like if I just pull individual table data then it works fine (i.e. e.PAGE.First() .. or .. e.CONTROL.Where(x=>x.someValue.Equals('someValue') ) but if I try to pull by traversing through the tables then I get nothing back (NULL).
Hope that all makes sense.
Some questions for you:
I assume is a 1..1 between PAGE and CONTROL,
Is there a FK called "ControlID" on PAGE?
Do you have a navigational property called "Control" on your "Page" entity in your EDMX?
If the answer to all of the above is Yes, then this should work:
var page = e.Pages.Include("Control").First();
Here, you are returning the First "Page" record, and eager loading the associated control.
The SQL produced should be something like this:
SELECT p.*, c.*
FROM Page p
INNER JOIN Control c
on p.ControlId = c.ControlId