Making my first steps in RIA Services (VS2010Beta2) and i encountered this problem:
created an EF Model (no POCOs), generic repository on top of it and a RIA Service(hosted in an ASP.NET MVC application) and tried to get data from within the ASP.NET MVC application: worked well.
Next step: Silverlight client. Got a reference to the RIAService (through its context), queried for all the records of the repository and got them into the SL application as well (using this code sample):
private ObservableCollection<Culture> _cultures = new ObservableCollection<Culture>();
public ObservableCollection<Culture> cultures
{
get { return _cultures; }
set
{
_cultures = value;
RaisePropertyChanged("cultures");
}
}
....
//Get cultures
EntityQuery<Culture> queryCultures = from cu in dsCtxt.GetAllCulturesQuery()
select cu;
loCultures = dsCtxt.Load(queryCultures);
loCultures.Completed += new EventHandler(lo_Completed);
....
void loAnyCulture_Completed(object sender, EventArgs e)
{
ObservableCollection<Culture> temp=
new ObservableCollection<Culture>loAnyCulture.Entities);
AnyCulture = temp[0];
}
The problem is this: whenever i try to edit some data of a record (in this example the first record) i get this error:
This EntitySet of type 'Culture' does not support the 'Edit' operation.
I thought that i did something weird and tried to create an object of type Culture and assign a value to it: it worked well!
What am i missing? Do i have to declare an EntitySet? Do i have to mark it? Do i have to...what?
Thanks in advance
It turns out that in the DomainService class one has to implement (or at least to mark "placeholder methods") as "Edit", "Delete",... eg
[Delete]
public void DeleteCulture(Culture currentCulture)
{
throw new NotImplementedException("UpdateCulture not Implemented yet");
}
[Insert]
public void InsertCulture(Culture newCulture)
{
throw new NotImplementedException("InsertCulture not Implemented yet");
}
This way the OrganizationDomainContextEntityContainer class creates an EntitySet with parameter EntitySetOperations.All (meaning that all the CUD operations are available).
Hope it's useful for someone in the future!
Related
When attempting to edit a new (proxy) entity using RequestFactoryEditorDriver.edit() I am getting the following error: "Exception caught: Attempting to edit an EntityProxy previously edited by another RequestContext". I am fairly sure that this is a result of my misunderstanding of the request factory/editor framework architecture. Here is the editor code that I think pertains to this problem:
public class OrgMaintenanceWidget extends Composite implements Editor<IOrgProxy> {
... other fields ...
private IOrgEditorDriver _orgEditorDriver;
interface IOrgEditorDriver extends RequestFactoryEditorDriver<IOrgProxy, OrgMaintenanceWidget> {}
public OrgMaintenanceWidget(final IClientFactory clientFactory) {
... widget initialization ...
_orgEditorDriver = GWT.create(IOrgEditorDriver.class);
_orgEditorDriver.initialize(_clientFactory.getRequestFactory().getEventBus(),
_clientFactory.getRequestFactory(), this);
}
#UiHandler("newButton")
public void onNewButtonClick(final ClickEvent clickEvent) {
_org = _clientFactory.getCache().getOrgCache().newOrg();
_orgEditorDriver.edit(_org, _clientFactory.getRequestFactory().orgRequestContext());
}
...
}
It's the "_orgEditorDriver.edit()" line that causes the exception. The "newOrg()" method is:
public IOrgProxy newOrg() {
return _clientFactory.getRequestFactory().orgRequestContext().create(IOrgProxy.class);
}
The RequestFactory is simply:
public interface IRequestFactory extends RequestFactory {
IOrgRequestContext orgRequestContext();
}
I am sure that I'm missing something fundamental about editing a new entity. When I edit an existing entity everything is fine ... the UI components are populated automatically, and flushing the editor back to the entity works very nicely. Here's the code that initiates editing for an existing entity:
#UiHandler("newButton")
public void onNewButtonClick(final ClickEvent clickEvent) {
_org = _clientFactory.getCache().getOrgCache().newOrg();
_orgEditorDriver.edit(_org, _clientFactory.getRequestFactory().orgRequestContext());
}
Any help would be greatly appreciated, and I'll try to publish any lessons learned.
This code:
_clientFactory.getRequestFactory().orgRequestContext().create(IOrgProxy.class);
Means:
Create new orgRequestContext()
Create new IOrgProxy using this context
Edit new IOrgProxy using this context, because as docs say: "Returns a new mutable proxy that this request can carry to the server, perhaps to be persisted.", it means that the proxy is edited by this request.
This code:
_orgEditorDriver.edit(_org, _clientFactory.getRequestFactory().orgRequestContext());
Means:
Again, create new orgRequestContext() (because each invocation of getRequestFactory().orgRequestContext() provides new instance of orgRequestContext()
"Start driving the Editor and its sub-editors with data." as docs say. But as a part of it, use passed orgRequestContext() to edit passed IOrgProxy instance, so that the proxy is editable.
Because the proxy was already edited while created by other RequestContext, you get the exception, because there is fundamental rule in RequestFactory, that proxy can be edited only by one RequestContext.
See also this thread.
I think you can't create an object with one RequestContext and then edit it with another one.
So you can solve this in two ways:
Persist the created object with the RequestContext you used when you created the object. The save method should return the persisted object and this persisted object can be passed to the editor with a fresh new RequestContext
Somewhere save the RequestContext you used for creating the object and pass it to the edit function of your Driver
Solution two could look something like this:
#UiHandler("newButton")
public void onNewButtonClick(final ClickEvent clickEvent) {
IOrgRequestContext ctx = _clientFactory.getRequestFactory().orgRequestContext();
_org = ctx.create(IOrgProxy.class);
_orgEditorDriver.edit(_org,ctx );
}
If I don't add Insert and Update methods to my domain service, I get exceptions when I try to add entities to the associated EntityCollection of my Entity. Now that I've added them (completely blank) I can add entities and modify them on the client but they never show up in my database. What am I missing? Do I need to create my own Insert and Update methods to my domain service and if so, what on earth would I put in them?
Edits:
This is what I have in my DomainContext. This seems a bit superfluous; I would think the Entity
Framework would already do this.
[Update]
public void UpdateProject(Project a_project)
{
ObjectContext.AcceptAllChanges();
}
[Update]
public void UpdateProjectItem(ProjectItem a_projectItem)
{
ObjectContext.AcceptAllChanges();
}
[Insert]
public void InsertProjectItem(ProjectItem a_projectItem)
{
ObjectContext.ProjectItems.AddObject(a_projectItem);
ObjectContext.AcceptAllChanges();
}
And this is how I'm using this on the client.
ProjectItem projectItem = new ProjectItem();
_reservedProject.Status = Project.ProjectStatusSubmitted;
_reservedProject.ProjectItems.Add(projectItem);
projectItem.LibraryItem = a_item;
_projectItems.Add(projectItem);
_domainContext.SubmitChanges();
UpdateProjectItem is never called.
I want to perform a generic insert in entity framework. This is what I wrote -
static public void Insert<T>(MyEntities DataContext, T obj) where T : class
{
try
{
DataContext.AddObject(DataContext,obj);
DataContext.SaveChanges();
}
catch (Exception e)
{
throw new Exception("Problems adding object" + e);
}
}
But as you can see the AddObject method is not what i want...it gives exception as it expects an enitysetname I want to pass in the object and then add that object to my database. But I cannot do AddtoObjectName() as I dont know the object. Can anyone point me in the right direction here..
In EF 4 you can do:
var os = DataContext.CreateObjectSet<T>();
os.AddObject(obj);
DataContext.SaveChanges();
And please remove the stack-eating try/catch.
The problem is that the Entity Framework allows for the possibility of multiple sets that use the same type, so it must have a type name in order to work. If you know that you won't be using multiple sets with the same type, you can follow a naming convention that makes it possible to construct the name from the type.
We had the same issue, and we originally decided to name each entity set [Type]Set (e.g. FormSet, ActivitySet).
With the advent of .NET 4.0, Microsoft has exposed the API they use for pluralizing entity sets in the EF tool in Visual Studio, so we're looking at maybe sticking with the default plurals, and using that tool to figure out what the default name is (e.g. Forms, Activities).
using System.Data.Entity.Design.PluralizationServices;
...
internal static readonly PluralizationService PluralizationService =
PluralizationService.CreateService(CultureInfo.CurrentCulture);
...
static public void Insert<T>(MyEntities DataContext, T obj) where T : class
{
try
{
string setName = PluralizationService.Pluralize(typeof(T).Name);
DataContext.AddObject(setName,obj);
DataContext.SaveChanges();
}
catch (Exception e)
{
throw new Exception("Problems adding object" + e);
}
}
If I run the following code it throws the following error:
An entity object cannot be referenced by multiple instances of IEntityChangeTracker
public void Save(Category category)
{
using(var db = new NorthwindContext())
{
if(category.CategoryID == 0)
{
db.AddToCategorySet(category);
}
else
{
//category.RemoveTracker();
db.Attach(category);
}
db.SaveChanges();
}
}
The reason is of course that the category is sent from interface which we got from GetById method which already attached the EntityChangeTracker to the category object. I also tried to set the entity tracker to null but it did not update the category object.
protected void Btn_Update_Category_Click(object sender, EventArgs e)
{
_categoryRepository = new CategoryRepository();
int categoryId = Int32.Parse(txtCategoryId.Text);
var category = _categoryRepository.GetById(categoryId);
category.CategoryName = txtUpdateCategoryName.Text;
_categoryRepository.Save(category);
}
I'm still learning Entity Framework myself, but maybe I can help a little. When working with the Entity Framework, you need to be aware of how you're handling different contexts. It looks like you're trying to localize your context as much as possible by saying:
public void Save(Category category)
{
using (var db = new NorthwindContext())
{
...
}
}
... within your data access method. Did you do the same thing in your GetById method? If so, did you remember to detach the object you got back so that it could be attached later in a different context?
public Category GetById(int categoryId)
{
using (var db = new NorthwindContext())
{
Category category = (from c in db.Category where Category.ID == categoryId select c).First();
db.Detach(category);
}
}
That way when you call Attach it isn't trying to step on an already-attached context. Does that help?
As you pointed out in your comment, this poses a problem when you're trying to modify an item and then tell your database layer to save it, because once an item is detached from its context, it no longer keeps track of the changes that were made to it. There are a few ways I can think of to get around this problem, none of them perfect.
If your architecture supports it, you could expand the scope of your context enough that your Save method could use the same context that your GetById method uses. This helps to avoid the whole attach/detach problem entirely, but it might push your data layer a little closer to your business logic than you would like.
You can load a new instance of the item out of the new context based on its ID, set all of its properties based on the category that is passed in, and then save it. This costs two database round-trips for what should really only need one, and it isn't very maintainable.
You can dig into the context itself to mark the Category's properties as changed.
For example:
public void Save(Category category)
{
using (var db = new NorthwindContext())
{
db.Attach(category);
var stateEntry = db.ObjectStateManager.GetObjectStateEntry(category);
foreach (var propertyName in stateEntry.CurrentValues.DataRecordInfo.FieldMetadata.Select(fm => fm.FieldType.Name)) {
stateEntry.SetModifiedProperty(propertyName);
}
db.SaveChanges();
}
}
This looks a little uglier, but should be more performant and maintainable overall. Plus, if you want, you could make it generic enough to throw into an extension method somewhere so you don't have to see or repeat the ugly code, but you still get the functionality out of it.
I have a model in Ado.Net EF.
I have a one to many relation and when I want to Add the entities I get the error
"An entity object cannot be referenceed by multiple instances of IEntityChangeTracker"
Any clue?
Something similar to
Template template = new Template();
...
...
while (from < to)
{
Course course = new Course();
.....
template.Course.Add(course);
.....
}
courseEntities.AddToTemplate(template); // Problem line
courseEntities.SaveChanges();
I was getting this message until i started to store the data context in the HttpContext.Items Property. This means you can use the same data context for the current web request. That way you don't end up with 2 data contexts referencing the same entities.
Here is a good post on DataContext Life Management.
I hope it helps.
Dave
"template", or something that it references, has already been added to courseEntities or another context. I don't see anything in the code you show it would do that, but it is certainly happening. Perhaps it's happening in some of the code that you've trimmed. Look at the EntityState property of "template" in the debugger, and look at the EntityState of the properties of "template" as well. This should help you find out which entity instance is already in a context.
I already realize the problem. I have another relation and I get the other entity from another context.
Let me relate my experience with this nasty error and point out the terrain chasing it will take you over leading to a tremendously simple solution.
CompanyGroup is pretty simple. It has a name and it has a Company object.
I started with this:
1 public static void Add(CompanyGroup item)
2 {
3 try
4 {
5 using (Entities scope = new Entities())
6 {
7 scope.AddToCompanyGroup(item);
8 scope.SaveChanges();
9 }
10 }
11 catch (Exception ex)
12 {
13 LogException(ex, item);
14 throw;
15 }
16 }
And got this error:
{"An entity object cannot be
referenced by multiple instances of
IEntityChangeTracker."}
So, I added this between lines 6 and 7:
(IEntityWithChangeTracker)item).SetChangeTracker(null);
That rewarded me with:
{"The object cannot be added to the
ObjectStateManager because it already
has an EntityKey. Use
ObjectContext.Attach to attach an
object that has an existing key."}
So I changed
scope.AddToCompanyGroup(item);
to
scope.Attach(item);
Now it complained about:
{"An object with a temporary EntityKey
value cannot be attached to an object
context."}
(beginning to sound like some of the girls I dated in my youth -- never content -- but I digress)
So I made the entity key null (didn't work) and used the method to create new (didn't work, either)
Along the way, I got this error, too:
{"The source query for this
EntityCollection or EntityReference
cannot be returned when the related
object is in either an added state or
a detached state and was not
originally retrieved using the
NoTracking merge option."}
The Solution?
Replace the core, lines 7 and 8, with:
CompanyGroup newcg = new CompanyGroup();
newcg.GroupName = item.GroupName;
newcg.Company = scope.Company.Where(c => c.CompanyID == item.Company.CompanyID).First();
scope.AddToCompanyGroup(newcg);
scope.SaveChanges();
Essentially, I took the data passed via 'item', and moved it to newly created object of the same type that introduces the same
scope as the one used in the Add.
I hope this is the simplest and correct solution. You need one db context per httprequest.
EF4 Code First template Global.asax.cs
http://gist.github.com/574505
void MvcApplication_BeginRequest(object sender, EventArgs e)
{
HttpContext.Current.Items[SessionKey] = new Db();
}
void MvcApplication_EndRequest(object sender, EventArgs e)
{
var disposable = HttpContext.Current.Items[SessionKey] as IDisposable;
if (disposable != null)
disposable.Dispose();
}
Please initialize your Entities only one time.
Like as
If You more than one time initialize your Entities.
You will get the error:
An entity object cannot be referenced by multiple instances of IEntityChangeTracker.
ex:
public class Test
{
private Entities db=new Entities();
public static void Add(CompanyGroup item)
{
try
{
db.CompanyGroup.Add(item);
db.SaveChanges();
}
catch (Exception ex)
{
}
}
}
This problem I was solved by removing from the object that I update, extra relationships with other entities (Virtual). Left only their ID.
This is wrong code
dataFileEntity.IterParameterValue = parameterValueEntity.ParameterValue;
dataFileEntity.IterParameterValueId = parameterValueEntity.ParameterValue.Id;
dataFileEntity.ResultParameter = parameterValueEntity.ResultParameter;
dataFileEntity.ResultParameterId = parameterValueEntity.ResultParameter.Id;
dataFileEntity.RawDataResult = result.Value;
This is right
dataFileEntity.IterParameterValueId = parameterValueEntity.ParameterValue.Id;
dataFileEntity.ResultParameterId = parameterValueEntity.ResultParameter.Id;
dataFileEntity.RawDataResult = result.Value;
RequestTestRawDataFileRepository.AddOrUpdate(dataFileEntity);
Я эту проблему решила, убрав из объекта, который я апдейтила лишние связи с другими сущностями (Virtual). Оставила только их id.