Unloading a data reference in Entity Framework - wcf

Currently I am struggling with a Entity Framework issue. I have a wcf service that sits on top of the ef framework, and allows queries to the framework. At some point the user is able to request a file from the framework. The files are referenced by solution entries, so when you request a file from a solution, the reference is loaded to gain access to the file store.
That all works fine, but from that point onward, whenever you do another query that returns that solution entry, the whole file gets attached to the return result. I need some way of detaching or unloading the reference, such that the result entries will only contain an unloaded reference to the file store again.
I have tried to create a new context and query that context to retrieve information from, but when I do that, the entity in the original context is also changed.
I have tried to detach the entity from the original context and then query from the new context. That does not work either.
I have found one way of doing this. For all the non file-download queries, I detach the result entity, and send that over the wire. I am not sure if that is the best way to go about it though.
I hope someone might be able to provide some insight, thanks for the effort.

The issue you are experiencing is probably do to Change Tracking, which is on by default.
Possible Solution:
Disable Change Tracking with MergeOption.NoTracking
using (MyEntities _context = new MyEntities())
{
_context.Widgets.MergeOption = MergeOption.NoTracking;
return _context.Widgets.ToList();
}
This article may help to point you in the right direction on how to handle this issue if the solution above does not work.
I struggled with a similar issue recently. The problem was the result of the context maintaining a reference to the object I was using (obviously). Every time I made a change to an object of the same type, even when obtained with a new context (so I thought), the object was being changed.
With help from one of my peers, we determined the context was hanging around due to the way I was registering it with my IoC container (lifestyle per web request). When I changed the lifestyle to transient (which definitively provided a new instance) then changes to objects of the same type were unaffected.
Hope this helps.

Related

How to intercept RavenDb Session.SaveChanges()

I am looking for a way to intercept Session.SaveChanges() so that I may execute some extra work using the same session instance (this is handy in some cases).
Edit: The point about re-using the session is that I have more work that needs to run in the same transaction.
I am already aware of (and make use of) IDocumentStoreListener - but this interface doesn't help because it does not give me access to the current session.
I can't find anything in RavenDb documentation about a way to intercept the call to SaveChanges and get a handle on the current session. Does anyone know of a way?
Open a new session it's free (in terms of performance), I think that IDocumentStoreListener has been thought for what you're looking for. I don't know other that works as you say.
implementing
void AfterStore(string key, object entityInstance, RavenJObject metadata);
you have all the information about the stored entity and then you can do what you need

LINQPad Dump() method not working for Sharepoint Client Object Model

I'm using LINQPad (2.42) to test some snippets that make use of SharePoint Client Object Model.
Basically messing with SPSite, SPWeb, SPList, SPFolder and SPFile.
The problem is that LINQPad seems to dislike calling .Dump() for any of the previous objects. It just keeps "Executing" for ever without showing any results.
Does anyone experience the same problem? Any workaround or fix?
Thanks
Try calling .Dump(0) to only dump the first level of Properties, or dumping the results to a Grid.
I have not looked at the SharePoint Client Objects but if they are anything like the TFS API classes, some of the properties are lazy loaded. Calling .Dump() will walk it's way down each every single result making server calls for every property (and property of property, etc.). This is probably what's taking the time.

Item is not added into the list (from code)

We have some strange problem here. We have feature event receiver, where we are creating custom fields -> content type -> list. After that, one default item is added. On my VM it was working just fine, but after moving into pre-prod environment, we got this strange behavior with no exception or error in logs.
First thing, item was created only sometimes, with no trace what happened. Mostly it was not created. I even experienced this: when I activated feature, I went to the list and so item there, but after refresh it was gone!
We tried to put there some Thread.Sleep() cycle (while debugging, item was in Items collection, but ItemsCount property of the list was always showing 0).
Now I am out of ideas what is wrong. It's not about execution time (maybe). Looks like, for some reason, SP is killing SPItem.Update before it is created for real and we don't know why. Any help is really welcome!
When you try to access sharepoint items from code and not have admin permissions to update/ delete them then set website website.AllowUnsafeUpdates = true; property
//Set AllowUnsafeUpdates = true to update the database / sharepoint list from code.
FormWeb.AllowUnsafeUpdates = true;
NewItem.Update();
FormWeb.AllowUnsafeUpdates = false;
you code should be like this to make changes in the list.. when you adding item to list.
Use Update statement in same manner when you accessing list and updating its data.
Check whether you updating the list correctly.. There may be some SharePoint security issue.
Reference Link:
http://blogs.msdn.com/b/infopath/archive/2010/04/01/add-items-to-a-sharepoint-list-using-managed-code.aspx.
You can check this [SPSecurity.RunWithElevatedPrivileges][1]
[1]: http://msdn.microsoft.com/en-us/library/microsoft.sharepoint.spsecurity.runwithelevatedprivileges.aspx , link, link
you can check that what is going over there by adding your events in sharepoint..
Check this post and debug it..
http://developmentsolutionsjunction.blogspot.com/2011/06/adding-events-and-eventhandlers-in.html
so I was finally able to find out where the problem was. After deeper study and trying that and this I found out that there was a third party feature. It was adding event to each created list and was deleting everything what wasn't consistent with CT defined by company. This is weird and I don't really understand why somebody wants this. But ok, they pay, their rules.
So if you encounter such problem, try also this possibility.
However, I also leard few things during this, e.g. if you are working with SP instances from web scope, use web scoped features, not site ones, also, SP has a nasty habit to silent som exceptions. Also, if you e.g. take instance of SPWeb from event properties, it doesn't necessarily means it is already created. It takes some time, also, Update() itself is a thing that DB has to perform. Sometimes it's better to alsways check if you really have instance and if not, threadsleep for a while.
Have you used .Update() method in your code??

Restore one RCP view while restoring another

Two views in my application need to load same information when restoring state. My idea was, to avoid saving it twice, to have one view create another in init orcreatePartControl if it wasn't created yet. However,
PlatformUI.getWorkbench().getActiveWorkbenchWindow().getActivePage().showView(...)
doesn't work there, as getActivePage() returns null. Is it possible to work around this?
Delegate to a manager or service to load/maintain/save the shared state. That will ensure the first access initializes your information. When the view is instantiated just go to the manager and retrieve the information. If the user never instantiates your view, then you never had to do the extra work.
In the general case, you can't create/instantiate one view while creating/activating another view. Eclipse won't allow it, and will generate ERRORs in the error log.
EDIT:
3 standard persistence patterns I've seen used (and/or misused :-) are:
1) Have your plugin get its state location and simply serialize you state out there. (location provided for free if you subclass org.eclipse.core.runtime.Plugin) You can do it in your activator stop(BundleContext) method. You can uses classes like org.eclipse.ui.XMLMemento to serialize to/from XML if you don't already have a solution.
2) if you subclass org.eclipse.ui.plugin.AbstractUIPlugin you can use org.eclipse.ui.plugin.AbstractUIPlugin.getDialogSettings() to store your state. Potentially a little bulky as you would have to keep it up to date.
3) have your common manager update a preference, potentially using another serialization technique.

Why is my Navigation Properties empty in Entity Framework 4?

The code:
public ChatMessage[] GetAllMessages(int chatRoomId)
{
using (ChatModelContainer context = new ChatModelContainer(CS))
{
//var temp = context.ChatMessages.ToArray();
ChatRoom cr = context.ChatRooms.FirstOrDefault(c => c.Id == chatRoomId);
if (cr == null) return null;
return cr.ChatMessages.ToArray();
}
}
The problem:
The method (part of WCF-service) returns an empty array. If I uncomment the commented line it starts working as expected. I have tried turning of lazy loading but it didnt help.
Also, when it works, I get ChatMessages with a reference to ChatRoom populated but not the ChatParticipant. They are both referenced by the ChatMessage-entity in the schema with both Id and Navigation Properties. The Ids are set and points to the right entities but on the client-side only the ChatRoom-reference has been populated.
Related questions:
Is an array the preferred method to return collections of EF-entities like this?
When making a change in my model (edmx) Im required to run the "Generate Database from Model..."-option before I can run context.CreateDatabase(). Why? I get some error message pointing to old SSDL but I cant find where the SSDL is stored. Is this created when I run this "Generate Database..."-option?
Is it safe to return entire entity-graphs to the client? Ive read some about "circular reference exeptions" but is this fixed in EF4?
How and when is references populated in EF4? If I have lazy-loading turned on I suspect only entities I touch is populated? But with lazy loading turned off, should the entire graph be populated always then?
Are there any drawbacks of using self-updating entities over ordinary entities in EF4? I dont need self-updating right now but I might do later. Can I upgrade easily or should I start with self-updating from the start?
Why cant I use entity-keys with type string?
Each of your questions needs a separate answer, but I'll try to answer them as briefly as possible.
First of all, in the code sample you provided, you get a ChatRoom object and then try to access a related object that is not included in your query (ChatMessages). If lazy loading is turned off as you had suggested, then you will need the Include("ChatMessages") call in your query, so your LINQ query should look like this:
ChatRoom cr = context.ChatRooms.Include("ChatMessages").FirstOrDefault(c => c.Id == chatRoomId);
Please ensure that your connection string is in your config file as well.
For the related questions:
You can return collections in any way you choose - I have typically done them in a List object (and I think that's the common way), but you could use arrays if you want. To return as a list, use the .ToList() method call on your query.
I don't understand what you're trying to do here, are you using code to create your database from your EDMX file or something? I've typically used a database-first approach, so I create my tables etc then update my EDMX from the database. Even if you generate your DB from your model, you shouldn't have to run CreateDatabase in code, you should be able to run the generated script against your DB. If you are using code-only then you need to dump the EDMX file.
You can generally return entity graphs to the client, should handle ok.
EF4 should only populate what you need. If you use lazy loading, it will automatically load things that you do not include in your LINQ query when you reference them and execute the query (e.g. do a ToList() operation). This won't work so well if your client is across a physical boundary (eg a service boundary) obviously :) If you don't use lazy loading, it will load what you tell it to in your query and that is all.
Self tracking entities are used for n-tier apps, where objects have to be passed across physical boundaries (eg services). They come with an overhead of generated code for each object to keep track of its changes, they also generate POCO objects which are not dependent on EF4 (but obviously contain generated code that would make the tracked changes work with the EF4 tracker). I'd say it depends on your usage, if you're building a small app that's quite self contained, and don't really care about separation for testability without the infrastructure in place, then you don't need to use self tracking entities. I say only use framework features when you need them, so if you're not writing an enterprise scale application (enterprise doesn't have to be big, but something scalable, highly testable, high quality etc) then no need to go for self tracking POCOs.
I haven't tried but you should be able to do that - that would be a candidate for a separate question if you can't get it to work :)