EF 4 Self Tracking Entities does not work as expected - entity-framework

I am using EF4 Self Tracking Entities (VS2010 Beta 2 CTP 2 plus new T4 generator). But when I try to update entity information it does not update to database as expected.
I setup 2 service calls. one for GetResource(int id) which return a resource object. the second call is SaveResource(Resource res); here is the code.
public Resource GetResource(int id)
{
using (var dc = new MyEntities())
{
return dc.Resources.Where(d => d.ResourceId == id).SingleOrDefault();
}
}
public void SaveResource(Resource res)
{
using (var dc = new MyEntities())
{
dc.Resources.ApplyChanges(res);
dc.SaveChanges();
// Nothing save to database.
}
}
//Windows Console Client Calls
var res = service.GetResource(1);
res.Description = "New Change"; // Not updating...
service.SaveResource(res);
// does not change anything.
It seems to me that ChangeTracker.State is always show as "Unchanged".
anything wrong in this code?

This is probably a long shot... but:
I assume your Service is actually in another Tier? If you are testing in the same tier you will have problems.
Self Tracking Entities (STEs) don't record changes until when they are connected to an ObjectContext, the idea is that if they are connected to a ObjectContext it can record changes for them and there is no point doing the same work twice.
STEs start tracking once they are deserialized on the client using WCF, i.e. once they are materialized to a tier without an ObjectContext.
If you look through the generated code you should be able to see how to turn tracking on manually too.
Hope this helps
Alex

You have to share assembly with STEs between client and service - that is the main point. Then when adding service reference make sure that "Reuse types in referenced assemblies" is checked.
The reason for this is that STEs contain logic which cannot be transfered by "Add service reference", so you have to share these types to have tracing logic on client as well.

After reading the following tip from Daniel Simmons, the STE starts tracking. Here is the link for the full article. http://msdn.microsoft.com/en-us/magazine/ee335715.aspx
Make certain to reuse the Self-Tracking Entity template’s generated entity code on your client. If you use proxy code generated by Add Service Reference in Visual Studio or some other tool, things look right for the most part, but you will discover that the entities don’t actually keep track of their changes on the client.
so in the client make sure you don't use add service reference to get the proxy instead access service through following code.
var svc = new ChannelFactory<IMyService>("BasicHttpBinding_IMyService").CreateChannel();
var res = svc.GetResource(1);

If you are using STEs without WCF you may have to call StartTracking() manually.

I had the same exact problem and found the solution.
It appears that for the self-tracking entities to automatically start tracking, you need to reference your STE project before adding the service reference.
This way Visual Studio generates some .datasource files which does the final trick.
I found the solution here:
http://blogs.u2u.be/diederik/post/2010/05/18/Self-Tracking-Entities-with-Validation-and-Tracking-State-Change-Notification.aspx
As for starting the tracking manually, it seems that you do not have these methods on the client-side.
Hope it helps...

Related

EntityFrameworkCore: How to initialize a Database and seed it the first time user uses an application

I have build a project using Microsoft Visual Studio 2015 and EntityFrameworkCore.
I have seed manually a couple of dummy data and I was developing my solution. Now, I want to deploy the in the server, but I get the problem that by starting the application the first time, it crash since it does not find a data base and data.
I have googled and I find the solution for Visual Studio 2013 and previous using the CreateDatabaseIfNotExists class that need the package: System.Data.Entity
(http://www.entityframeworktutorial.net/code-first/database-initialization-strategy-in-code-first.aspx), however, such classes and packages do not exist in EntityFrameworkCore.
How does I create and populate a database with at least one row if user is using my application by the first time in EntityFrameworkCore?
or which is the equivalent to System.Data.Entity in Entity Framework Core?
Rowan Miller says that ApplyMigrations is enough to create database (if not exist) and apply all (nesessary) migrations.
Create method like this:
public void CreateDbAndSampleData(IServiceProvider applicationServices)
{
using (var serviceScope = applicationServices.GetRequiredService<IServiceScopeFactory>().CreateScope())
{
using (var db = serviceProvider.GetService<ApplicationDbContext>())
{
// This will [try to] create database
// and apply all necessary migrations
db.Database.AsRelational().ApplyMigrations();
// then you can check for existing data and modify something
var admin = db.Users.Where(x => x.Name == "Superadmin").FirstOrDefault();
if (admin == null)
{
db.Users.Add(new User {...});
db.SaveChanges();
}
}
}
}
And call it from your Startup.cs, at end of Configure method:
CreateDbAndSampleData(app.ApplicationServices);
This code will run on every app startup, so you need to be accurate and do not overwrite any non-critical data changes (like changing Users's comment etc)
You can use MusicStore app as a sample: Startup.cs and SampleData.cs

Unity Entity Framework within ASP.NET WebAPI 2

I have a very weird problem with Unity here. I have the following:
public class UnityConfig
{
public static void RegisterTypes(IUnityContainer container)
container.RegisterType<IDBContext, MyDbContext>(new PerThreadLifetimeManager());
container.RegisterType<IUserDbContext>(new PerThreadLifetimeManager(), new InjectionFactory(c =>
{
var tenantConnectionString = c.Resolve<ITenantConnectionResolver>().ResolveConnectionString();
return new UserDbContext(tenantConnectionString);
}));
}
}
and then in the WebApiConfig.cs file within the Reigster method:
var container = new UnityContainer();
UnityConfig.RegisterTypes(container);
config.DependencyResolver = new UnityResolver(container);
Basically, what I want to happen in the above code is on every request to the API, I want Unity to new up a UserDbContext based on the user (multi-tenant kind of environment). Now the TenantConnectionResolver is responsible for figuring out the Connection String and then I use that connection string to new up UserDbContext.
Also note (not shown above) that TenantConnectionResolver takes an IDbConext in its constructor because I need it to figure out the connection string based on user information in that database.
But for some reason, the code within the InjectionFactory runs at random times. For example, I call //mysite.com/controller/action/1 repetitively from a browser, the code in the InjectionFactory will occasionally run but not on each request.
Am I incorrectly configuring Unity? Has anybody encountered anything similar to this?
Thanks in advance
The problem is very likely related to the LifetimeManager you are using. PerThreadLifetimeManager is not adapted in a web context, as threads are pooled and will serve multiple requests in sequence.
PerRequestLifetimeManager is probably what you want to use.

Breeze: cannot execute _executeQueryCore until metadataStore is populated

I was using Breeze v1.1.2 that came with the Hot Towel template which has now been extended to form my project. I made the mistake of updating the NuGet package to the current 1.3.3 (I never learn). Anyway, all was well, and now not so much!
I followed the instructions in the release notes and other docs to change my BreezeWebApiConfig file to:
[assembly: WebActivator.PreApplicationStartMethod(
typeof(BreezeWebApiConfig), "RegisterBreezePreStart")]
namespace MyApp.App_Start {
public static class BreezeWebApiConfig {
public static void RegisterBreezePreStart() {
GlobalConfiguration.Configuration.Routes.MapHttpRoute(
name: "BreezeApi",
routeTemplate: "breeze/{controller}/{action}"
);}}}
And the config.js file (which provides the serviceName to the EntityManager constructor) to:
var remoteServiceName = 'breeze/breeze'; // NEW version
//var remoteServiceName = 'api/breeze'; // OLD version
And my BreezeController if you're interested:
[BreezeController]
public class BreezeController : ApiController
{
readonly EFContextProvider<MyDbContext> _contextProvider =
new EFContextProvider<MyDbContext>();
[HttpGet]
public string Metadata()
{
return _contextProvider.Metadata();
}
[HttpGet]
public IQueryable<SomeItem> SomeItems()
{
// Do stuff here...
}
}
Now I get the "cannot execute _executeQueryCore until metadataStore is populated" error.
What am I missing here?
EDIT:
I perhaps left out the part you needed... Above in the SomeItems() method, the stuff that actually gets done is a call to the GetMeSomeData() method in the MyDBContext class. This method makes the following call to a stored procedure to get the data.
public virtual ObjectResult<SomeItem> GetMeSomeData(string inParam)
{
var p = new object[] { new SqlParameter("#inParam", inParam) };
var retVal = ((IObjectContextAdapter)this).ObjectContext.ExecuteStoreQuery<SomeItem>("exec GetData #SN", p);
return retVal;
}
Now given my limited understanding, the call to Metadata() is not failing, but I don't think it has any idea what the entity model is when coming back, even though somewhere along the line, it should figure that out from the entity model I do have (i.e. SomeItem)? The return string from Metadata() doesn't have any information about the entity. Is there a way to make it aware? Or am I just completely off in left field playing with the daisies?
Hard to say based on this report. Let's see if Breeze is right.
Open the browser debugging tools and look at the network traffic. Do you see an attempt to get metadata from the server before you get that error? If so, did it succeed? Or 404? Or 500? What was the error?
I'm betting it didn't even try. If it didn't, the usual reason is that you tried some Breeze operation before your first query ... and you didn't ask for metadata explicitly either. Did you try to create an entity? That requires metadata.
The point is, you've got to track down the Breeze operation that precipitates the error. Sure everything should just work. The world should be rainbows and unicorns. When it isn't, we heave a sigh, break out the debugger, and start with the information that the error gave us.
And for the rest of you out there ... upgrading to a new Breeze version is a good thing.
Happy coding everyone.
Follow-up to your update
Breeze doesn't know how you get your data on the back-end. If the query result has a recognizable entity in it, Breeze will cache that. It's still up to you in the query callback to ensure that what you deliver to the caller is something meaningful.
You say that you're server-side metadata method doesn't have any idea what SomeItem is? Then it's not much use to the client. If it returns a null string, Breeze may treat that as "no metadata at all" in which case you should be getting the "cannot execute _executeQueryCore until metadataStore is populated" error message. Btw, did you check the network traffic to determine what your server actually returned in response to the metadata request (or if there was such a request)?
There are many ways to create Metadata on the server. The easiest is to use EF ... at least as a modeling tool at design time. What's in that MyDbContext of yours? Why isn't SomeItem in there?
You also can create metadata on the client if you don't want to generate it from the server. You do have to tell the Breeze client that you've made that choice. Much of this is explained in the documentation "Metadata Format".
I get the feeling that you're kind of winging it. You want to stray from the happy path ... and that's cool. But most of us need to learn to walk before we run.

ObjectContext.Attach generates incorrect entity key

I'm using .NET 4.0 with EF POCO's. I have a conceptual model from which a part is shown in the image. Everything works fine, except one thing which I have been almost busy with for 2 days and still don't get it to work!
In my conceptual model, a WebShop can have one or more related WebShopCategory instances. Each WebShopCategory associates a WebShop with a Category and enables me to specify additional properties for a WebShop/Category combination.
See image here: http://postimage.org/image/djrn4xh37/
When creating a new WebShop instance of course I need to save it, which I do in an Update method of a WebShopRepository which uses the EF ObjectContext as shown in the code below:
using (MyEntities entities = new MyEntities()) {
if (webShop.ID == 0) {
entities.Countries.Attach(webShop.Country);
foreach (PaymentMethod paymentMethod in webShop.PaymentMethods) {
entities.PaymentMethods.Attach(paymentMethod);
}
foreach (QualityMark qualityMark in webShop.QualityMarks) {
entities.QualityMarks.Attach(qualityMark);
}
foreach (WebShopCategory category in webShop.Categories) {
entities.Categories.Attach(category.Category);
}
entities.WebShops.AddObject(webShop);
}
entities.SaveChanges();
}
One thing to note is that all related items already exist in the data source. As they are not yet in the ObjectContext, I've attached them before adding the created WebShop to the ObjectContext. This seems to work as expected: all entities that have been attached have an EntityState.Unchaged state which is correct. The added WebShop is in the Added state which also is correct.
However, it can happen that when I attach the Category instances (category.Category) EF gives an exception stating that there is already an item in the object context with the same key. I have found this ObjectStateEntry instance and what I noticed was that the EntityKey only consists of the EntitySet name, and not with the ID also in the key. Other EntityKeys that have been added to the context are all in the form of EntitySetName;ID=value
To me it seems that the entity key is somehow not being determined correctly by the EF, because at the point where it goes wrong I've checked and made sure that the added category is indeed valid: it is a category already known in the sytem and has its primary key (ID) value set to 1 (which is the first added category in the system).
I've tried many ways to fix this but cannot get this to work. Any help would be greatly appreciated!
Thank you all very much in advance!

How to use ADO.net Entity Framework with an existing SqlConnection?

I have an existing asp.net website that uses an SqlConnection.
I have added the ADO.net Entity Framework.
I have successfully connected to the database and created the .edmx file.
I am able to connect through the Entity Framework with the connectionstring that is automatically generated.
I want to use the existing SqlConnection object that I use throughout the site for the Entity Framework connection.
I do not want to have to use a second database connection for the one page that is going to use the ADO.net Entity Framework and I don’t want to change the entire site to use the new Entity Framework connection string.
Thanks for any help you can provide.
That forum post has the answer:
MetadataWorkspace workspace = new MetadataWorkspace(
new string[] { "res://*/" },
new Assembly[] { Assembly.GetExecutingAssembly() });
using (SqlConnection sqlConnection = new SqlConnection(connectionString))
using (EntityConnection entityConnection = new EntityConnection(workspace, sqlConnection))
using (NorthwindEntities context = new NorthwindEntities(entityConnection))
{
foreach (var product in context.Products)
{
Console.WriteLine(product.ProductName);
}
}
"res://*/" is the part of your EF connection string that describes the location of your xml mapping files - in this case embedded resources in the current assembly.
You can do this by using the constructor of your generated ObjectContext that accepts an EntityConnection. When you create the EntityConnection you pass in your SqlConnection.
Andrew Peters,
Thank you for your answer.
I have been going around and around with the System.Data.EntityClient.EntityConnection.
It’s right there at my finger tips but I cannot seem to get the MetadataWorkspace parameter to work.
This is the closest example I have found (the post marked Answer):
http://social.msdn.microsoft.com/Forums/en-US/adodotnetentityframework/thread/dd7b1c41-e428-4e29-ab83-448d3f529ba4/
Thanks for any help.