Search Results

Search found 158 results on 7 pages for 'objectcontext'.

Page 1/7 | 1 2 3 4 5 6 7  | Next Page >

  • EF4: ObjectContext inconsistent when inserting into a view with triggers

    - by user613567
    I get an Invalid Operation Exception when inserting records in a View that uses “Instead of” triggers in SQL Server with ADO.NET Entity Framework 4. The error message says: {"The changes to the database were committed successfully, but an error occurred while updating the object context. The ObjectContext might be in an inconsistent state. Inner exception message: The key-value pairs that define an EntityKey cannot be null or empty. Parameter name: record"} @ at System.Data.Objects.ObjectContext.SaveChanges(SaveOptions options) at System.Data.Objects.ObjectContext.SaveChanges() In this simplified example I created two tables, Contacts and Employers, and one view Contacts_x_Employers which allows me to insert or retrieve rows into/from these two tables at once. The Tables only have a Name and an ID attributes and the view is based on a join of both: CREATE VIEW [dbo].[Contacts_x_Employers] AS SELECT dbo.Contacts.ContactName, dbo.Employers.EmployerName FROM dbo.Contacts INNER JOIN dbo.Employers ON dbo.Contacts.EmployerID = dbo.Employers.EmployerID And has this trigger: Create TRIGGER C_x_E_Inserts ON Contacts_x_Employers INSTEAD of INSERT AS BEGIN SET NOCOUNT ON; insert into Employers (EmployerName) select i.EmployerName from inserted i where not i.EmployerName in (select EmployerName from Employers) insert into Contacts (ContactName, EmployerID) select i.ContactName, e.EmployerID from inserted i inner join employers e on i.EmployerName = e.EmployerName; END GO The .NET Code follows: using (var Context = new TriggersTestEntities()) { Contacts_x_Employers CE1 = new Contacts_x_Employers(); CE1.ContactName = "J"; CE1.EmployerName = "T"; Contacts_x_Employers CE2 = new Contacts_x_Employers(); CE1.ContactName = "W"; CE1.EmployerName = "C"; Context.Contacts_x_Employers.AddObject(CE1); Context.Contacts_x_Employers.AddObject(CE2); Context.SaveChanges(); //? line with error } SSDL and CSDL (the view nodes): <EntityType Name="Contacts_x_Employers"> <Key> <PropertyRef Name="ContactName" /> <PropertyRef Name="EmployerName" /> </Key> <Property Name="ContactName" Type="varchar" Nullable="false" MaxLength="50" /> <Property Name="EmployerName" Type="varchar" Nullable="false" MaxLength="50" /> </EntityType> <EntityType Name="Contacts_x_Employers"> <Key> <PropertyRef Name="ContactName" /> <PropertyRef Name="EmployerName" /> </Key> <Property Name="ContactName" Type="String" Nullable="false" MaxLength="50" Unicode="false" FixedLength="false" /> <Property Name="EmployerName" Type="String" Nullable="false" MaxLength="50" Unicode="false" FixedLength="false" /> </EntityType> The Visual Studio solution and the SQL Scripts to re-create the whole application can be found in the TestViewTrggers.zip at ftp://JulioSantos.com/files/TriggerBug/. I appreciate any assistance that can be provided. I already spent days working on this problem.

    Read the article

  • ASP.Net Entity Framework, objectcontext error

    - by Chris Klepeis
    I'm building a 4 layered ASP.Net web application. The layers are: Data Layer Entity Layer Business Layer UI Layer The entity layer has my data model classes and is built from my entity data model (edmx file) in the datalayer using T4 templates (POCO). The entity layer is referenced in all other layers. My data layer has a class called SourceKeyRepository which has a function like so: public IEnumerable<SourceKey> Get(SourceKey sk) { using (dmc = new DataModelContainer()) { var query = from SourceKey in dmc.SourceKeys select SourceKey; if (sk.sourceKey1 != null) { query = from SourceKey in query where SourceKey.sourceKey1 == sk.sourceKey1 select SourceKey; } return query; } } Lazy loading is disabled since I do not want my queries to run in other layers of this application. I'm receiving the following error when attempting to access the information in the UI layer: The ObjectContext instance has been disposed and can no longer be used for operations that require a connection. I'm sure this is because my DataModelContainer "dmc" was disposed. How can I return this IEnumerable object from my data layer so that it does not rely on the ObjectContext, but solely on the DataModel? Is there a way to limit lazy loading to only occur in the data layer?

    Read the article

  • MVC ASP.NET, ObjectContext and Ajax. Weird Behaviour

    - by fabianadipolo
    Hi, i've been creating a web application in mvc asp.net. I have three different project/solutions. One solution contains the model in EF (DAL) and all the methods to add, update, delete and query the objects in the model, the objectcontext is managed here in a per request basis. Other solution contains a content management system in wich authorized users insert, delete, update and access objects through the DAL mentioned before. And the last solution contains the web page that is accessed by all users and where the only operations executed are selects, no update, inserts or deletes here. All the selects are executed against the DAL mentioned before (the first solution). The problem here is that i'm not sure whether an HttpContext lifespan ObjectContext is the best solution. I have a lot of ajax calls in my web app and i'm not sure if an httpcontext could interfere with the performance of the application. I've been noticed that in some cases, specially when someone is working in the content manager inserting, updating or deleting, when you try to click on any link of the user web application (the web app that is accessed by any user - the third one that i mentioned before) the web page freezes and it remains stucked transferring data. In order to stop that behaviour you have to stop and refresh or click several times on the link. Excuse me for my bad english. I hope you could understand and could help me to solve this issue. Thanx in advance.

    Read the article

  • EF4 - possible to mock ObjectContext for unit testing?

    - by steve.macdonald
    Can it be done without using TypeMock Islolator? I've found a few suggestions online such as passing in a metadata only connection string, however nothing I've come across besides TypeMock seems to truly allow for a mock ObjectContext that can be injected into services for unit testing. Do I plunk down the $$ for TypeMock, or are there alternatives? Has nobody managed to create anything comparable to TypeMock that is open source?

    Read the article

  • Different setter behavior between DbContext and ObjectContext

    - by Paul
    (This is using EntityFramework 4.2 CTP) I haven't found any references to this on the web yet, although it's likely I'm using the wrong terminology while searching. There's also a very likely scenario where this is 100% expected behavior, just looking for confirmation and would rather not dig through the tt template (still new to this). Assuming I have a class with a boolean field called Active and I have one row that already has this value set to true. I have code that executes to set said field to True regardless of it's existing value. If I use DbContext to update the value to True no update is made. If I use ObjectContext to update the value an update is made regardless of the existing value. This is happening in the exact same EDMX, all I did was change the code generation template from DbContext to EntityObject. Update: Ok, found the confirmation I was looking for...consider this a dupe...next time I'll do MOAR SEARCHING! Entity Framework: Cancel a property change if no change in value ** Update 2: ** Problem: the default tt template wraps the "if (this != value)" in the setter with "if (iskey), so only primarykey fields receive this logic. Solution: it's not the most graceful thing, but I removed this check...we'll see how it pans out in real usage. I included the entire tt template, my changes are denoted with "**"... //////// //////// Write SimpleType Properties. //////// private void WriteSimpleTypeProperty(EdmProperty simpleProperty, CodeGenerationTools code) { MetadataTools ef = new MetadataTools(this); #> /// <summary> /// <#=SummaryComment(simpleProperty)#> /// </summary><#=LongDescriptionCommentElement(simpleProperty, 1)#> [EdmScalarPropertyAttribute(EntityKeyProperty= <#=code.CreateLiteral(ef.IsKey(simpleProperty))#>, IsNullable=<#=code.CreateLiteral(ef.IsNullable(simpleProperty))#>)] [DataMemberAttribute()] <#=code.SpaceAfter(NewModifier(simpleProperty))#><#=Accessibility.ForProperty(simpleProperty)#> <#=MultiSchemaEscape(simpleProperty.TypeUsage, code)#> <#=code.Escape(simpleProperty)#> { <#=code.SpaceAfter(Accessibility.ForGetter(simpleProperty))#>get { <#+ if (ef.ClrType(simpleProperty.TypeUsage) == typeof(byte[])) { #> return StructuralObject.GetValidValue(<#=code.FieldName(simpleProperty)#>); <#+ } else { #> return <#=code.FieldName(simpleProperty)#>; <#+ } #> } <#=code.SpaceAfter(Accessibility.ForSetter((simpleProperty)))#>set { <#+ **//if (ef.IsKey(simpleProperty)) **//{ if (ef.ClrType(simpleProperty.TypeUsage) == typeof(byte[])) { #> if (!StructuralObject.BinaryEquals(<#=code.FieldName(simpleProperty)#>, value)) <#+ } else { #> if (<#=code.FieldName(simpleProperty)#> != value) <#+ } #> { <#+ PushIndent(CodeRegion.GetIndent(1)); **//} #> <#=ChangingMethodName(simpleProperty)#>(value); ReportPropertyChanging("<#=simpleProperty.Name#>"); <#=code.FieldName(simpleProperty)#> = <#=CastToEnumType(simpleProperty.TypeUsage, code)#>StructuralObject.SetValidValue(<#=CastToUnderlyingType(simpleProperty.TypeUsage, code)#>value<#=OptionalNullableParameterForSetValidValue(simpleProperty, code)#>, "<#=simpleProperty.Name#>"); ReportPropertyChanged("<#=simpleProperty.Name#>"); <#=ChangedMethodName(simpleProperty)#>(); <#+ //if (ef.IsKey(simpleProperty)) //{ PopIndent(); #> } <#+ //} #> } }

    Read the article

  • .Net Entity objectcontext thread error

    - by Chris Klepeis
    I have an n-layered asp.net application which returns an object from my DAL to the BAL like so: public IEnumerable<SourceKey> Get(SourceKey sk) { var query = from SourceKey in _dataContext.SourceKeys select SourceKey; if (sk.sourceKey1 != null) { query = from SourceKey in query where SourceKey.sourceKey1 == sk.sourceKey1 select SourceKey; } return query.AsEnumerable(); } This result passes through my business layer and hits the UI layer to display to the end users. I do not lazy load to prevent query execution in other layers of my application. I created another function in my DAL to delete objects: public void Delete(SourceKey sk) { try { _dataContext.DeleteObject(sk); _dataContext.SaveChanges(); } catch (Exception ex) { Debug.WriteLine(ex.Message + " " + ex.StackTrace + " " + ex.InnerException); } } When I try to call "Delete" after calling the "Get" function, I receive this error: New transaction is not allowed because there are other threads running in the session This is an ASP.Net app. My DAL contains an entity data model. The class in which I have the above functions share the same _dataContext, which is instantiated in my constructor. My guess is that the reader is still open from the "Get" function and was not closed. How can I close it?

    Read the article

  • How to convert a DataSet object into an ObjectContext (Entity Framework) object on the fly?

    - by Marcel
    Hi all, I have an existing SQL Server database, where I store data from large specific log files (often 100 MB and more), one per database. After some analysis, the database is deleted again. From the database, I have created both a Entity Framework Model and a DataSet Model via the Visual Studio designers. The DataSet is only for bulk importing data with SqlBulkCopy, after a quite complicated parsing process. All queries are then done using the Entity Framework Model, whose CreateQuery Method is exposed via an interface like this public IQueryable<TTarget> GetResults<TTarget>() where TTarget : EntityObject, new() { return this.Context.CreateQuery<TTarget>(typeof(TTarget).Name); } Now, sometimes my files are very small and in such a case I would like to omit the import into the database, but just have a an in-memory representation of the data, accessible as Entities. The idea is to create the DataSet, but instead of bulk importing, to directly transfer it into an ObjectContext which is accessible via the interface. Does this make sense? Now here's what I have done for this conversion so far: I traverse all tables in the DataSet, convert the single rows into entities of the corresponding type and add them to instantiated object of my typed Entity context class, like so MyEntities context = new MyEntities(); //create new in-memory context ///.... //get the item in the navigations table MyDataSet.NavigationResultRow dataRow = ds.NavigationResult.First(); //here, a foreach would be necessary in a true-world scenario NavigationResult entity = new NavigationResult { Direction = dataRow.Direction, ///... NavigationResultID = dataRow.NavigationResultID }; //convert to entities context.AddToNavigationResult(entity); //add to entities ///.... A very tedious work, as I would need to create a converter for each of my entity type and iterate over each table in the DataSet I have. Beware, if I ever change my database model.... Also, I have found out, that I can only instantiate MyEntities, if I provide a valid connection string to a SQL Server database. Since I do not want to actually write to my fully fledged database each time, this hinders my intentions. I intend to have only some in-memory proxy database. Can I do simpler? Is there some automated way of doing such a conversion, like generating an ObjectContext out of a DataSet object? P.S: I have seen a few questions about unit testing that seem somewhat related, but not quite exact.

    Read the article

  • Closing an EDM ObjectContext?

    - by David Veeneman
    I am getting started with the ADO.NET Entity Framework 4.0. I have created an EDM and data store for the app, and it successfully retrieves entities. The application holds the EDM's ObjectContext as a member-level variable, which it uses to call ObjectContext.SaveChanges(). So far, so good. I am going to refactor to repositories later. Right now, my question is a bit more basic: When I am finished with the EDM, what do I need to do to release it? Is it as simple as calling Dispose() on the ObjectContext? Thanks for your help.

    Read the article

  • Using Structuremap to manage ObjectContext Lifetime in ASP.NET MVC

    - by Diego Correa
    Hi, what I want to know If there is a way or an good article on how to manage the objectcontext life cycle through structuremap (I saw an example with ninject). Since I'm new to the methods and possibilities of SM I really don't know How/If possible to make it. In the first moment I wanted to make a singleton of the objectcontext per httpcontext. Thanks for any advice.

    Read the article

  • Entity Framework ObjectContext re-usage

    - by verror
    I'm learning EF now and have a question regarding the ObjectContext: Should I create instance of ObjectContext for every query (function) when I access the database? Or it's better to create it once (singleton) and reuse it? Before EF I was using enterprise library data access block and created instance of dataacess for DataAccess function...

    Read the article

  • ObjectContext disposed puzzle

    - by jaklucky
    Hi, I have the follwing method. public List<MyEntity> GetMyEntities(MyObjectContext objCtx) { using(MyObjectContext ctx = objCtx ?? new MyObjectContext()) { retun ctx.MyEntities.ToList(); } } The idea is, user of this method can pass in the objectcontext if they have. If not then a new objectcontext will be created. If I am passing an object context to it, then it is getting disposed after the method is done. I was expecting only "ctx" variable gets disposed. If I write a small app, to know the using and dispose mechanism. It is acting differently. class TestClass : IDisposable { public int Number { get; set; } public string Str { get; set; } public ChildClass Child { get; set; } #region IDisposable Members public void Dispose() { Console.WriteLine("Disposed is called"); } #endregion } class ChildClass : IDisposable { public string StrChild { get; set; } #region IDisposable Members public void Dispose() { Console.WriteLine("Child Disposed is called"); } #endregion } class Program { static void Main(string[] args) { TestClass test = null; test = new TestClass(); test.Child = new ChildClass(); using (TestClass test1 = test ?? new TestClass()) { test1.Number = 1; test1.Str = "hi"; test1.Child.StrChild = "Child one"; test1.Child.Dispose(); } test.Str = "hi"; test.Child.StrChild = "hi child"; Console.ReadLine(); } } In this example, "test1"gets disposed but not "test". Where as in the first case both ctx and objCtx get disposed. Any ideas what is happening here with objectContext? Thank you, Suresh

    Read the article

  • Problem creating ObjectContext from different project inside solution.

    - by Levelbit
    I have two projects in my Solution. One implements my business logic and has defined entity model of entity framework. When I want to work with classes defined within this project from another project I have some problems in runtime. Actually, the most concerning thing is why I can not instantiate my, so called, TicketEntities(ObjectContext) object from other projects? when I catch following exception: The specified named connection is either not found in the configuration, not intended to be used with the EntityClient provider, or not valid. I found out it's brake at: public partial class TicketEntities : global::System.Data.Objects.ObjectContext { public TicketEntities() : base("name=TicketEntities", "TicketEntities") { this.OnContextCreated(); } with exception: Unable to load the specified metadata resource. Just to remind you everthing works fine from orginal project.

    Read the article

  • Entity Framework ObjectContext Life-cycle

    - by Leonardo
    Hello, I'm developing a web application using asp.net 4.0 with Entity Framework. In my apllication I have a page DataEntry.aspx wich has 3 web user control.Each user control manage an entity and use a repository class to access data. The final user before save all the changes can add or remove entity in memory. My question is: how can i share the ObjectContext between the repositories? Basically I need a ObjectContext for the entire session working of DataEntry.aspx. How can I achive this? Thank you

    Read the article

  • ObjectContext.SaveChanges() fails with SQL CE

    - by David Veeneman
    I am creating a model-first Entity Framework 4 app that uses SQL CE as its data store. All is well until I call ObjectContext.SaveChanges() to save changes to the entities in the model. At that point, SaveChanges() throws a System.Data.UpdateException, with an inner exception message that reads as follows: Server-generated keys and server-generated values are not supported by SQL Server Compact. I am completely puzzled by this message. Any idea what is going on and how to fix it? Thanks. Here is the Exception dump: System.Data.UpdateException was unhandled Message=An error occurred while updating the entries. See the inner exception for details. Source=System.Data.Entity StackTrace: at System.Data.Mapping.Update.Internal.UpdateTranslator.Update(IEntityStateManager stateManager, IEntityAdapter adapter) at System.Data.EntityClient.EntityAdapter.Update(IEntityStateManager entityCache) at System.Data.Objects.ObjectContext.SaveChanges(SaveOptions options) at System.Data.Objects.ObjectContext.SaveChanges() at FsDocumentationBuilder.ViewModel.Commands.SaveFileCommand.Execute(Object parameter) in D:\Users\dcveeneman\Documents\Visual Studio 2010\Projects\FsDocumentationBuilder\FsDocumentationBuilder\ViewModel\Commands\SaveFileCommand.cs:line 68 at MS.Internal.Commands.CommandHelpers.CriticalExecuteCommandSource(ICommandSource commandSource, Boolean userInitiated) at System.Windows.Controls.Primitives.ButtonBase.OnClick() at System.Windows.Controls.Button.OnClick() at System.Windows.Controls.Primitives.ButtonBase.OnMouseLeftButtonUp(MouseButtonEventArgs e) at System.Windows.UIElement.OnMouseLeftButtonUpThunk(Object sender, MouseButtonEventArgs e) at System.Windows.Input.MouseButtonEventArgs.InvokeEventHandler(Delegate genericHandler, Object genericTarget) at System.Windows.RoutedEventArgs.InvokeHandler(Delegate handler, Object target) at System.Windows.RoutedEventHandlerInfo.InvokeHandler(Object target, RoutedEventArgs routedEventArgs) at System.Windows.EventRoute.InvokeHandlersImpl(Object source, RoutedEventArgs args, Boolean reRaised) at System.Windows.UIElement.ReRaiseEventAs(DependencyObject sender, RoutedEventArgs args, RoutedEvent newEvent) at System.Windows.UIElement.OnMouseUpThunk(Object sender, MouseButtonEventArgs e) at System.Windows.Input.MouseButtonEventArgs.InvokeEventHandler(Delegate genericHandler, Object genericTarget) at System.Windows.RoutedEventArgs.InvokeHandler(Delegate handler, Object target) at System.Windows.RoutedEventHandlerInfo.InvokeHandler(Object target, RoutedEventArgs routedEventArgs) at System.Windows.EventRoute.InvokeHandlersImpl(Object source, RoutedEventArgs args, Boolean reRaised) at System.Windows.UIElement.RaiseEventImpl(DependencyObject sender, RoutedEventArgs args) at System.Windows.UIElement.RaiseTrustedEvent(RoutedEventArgs args) at System.Windows.UIElement.RaiseEvent(RoutedEventArgs args, Boolean trusted) at System.Windows.Input.InputManager.ProcessStagingArea() at System.Windows.Input.InputManager.ProcessInput(InputEventArgs input) at System.Windows.Input.InputProviderSite.ReportInput(InputReport inputReport) at System.Windows.Interop.HwndMouseInputProvider.ReportInput(IntPtr hwnd, InputMode mode, Int32 timestamp, RawMouseActions actions, Int32 x, Int32 y, Int32 wheel) at System.Windows.Interop.HwndMouseInputProvider.FilterMessage(IntPtr hwnd, WindowMessage msg, IntPtr wParam, IntPtr lParam, Boolean& handled) at System.Windows.Interop.HwndSource.InputFilterMessage(IntPtr hwnd, Int32 msg, IntPtr wParam, IntPtr lParam, Boolean& handled) at MS.Win32.HwndWrapper.WndProc(IntPtr hwnd, Int32 msg, IntPtr wParam, IntPtr lParam, Boolean& handled) at MS.Win32.HwndSubclass.DispatcherCallbackOperation(Object o) at System.Windows.Threading.ExceptionWrapper.InternalRealCall(Delegate callback, Object args, Int32 numArgs) at MS.Internal.Threading.ExceptionFilterHelper.TryCatchWhen(Object source, Delegate method, Object args, Int32 numArgs, Delegate catchHandler) at System.Windows.Threading.Dispatcher.InvokeImpl(DispatcherPriority priority, TimeSpan timeout, Delegate method, Object args, Int32 numArgs) at MS.Win32.HwndSubclass.SubclassWndProc(IntPtr hwnd, Int32 msg, IntPtr wParam, IntPtr lParam) at MS.Win32.UnsafeNativeMethods.DispatchMessage(MSG& msg) at System.Windows.Threading.Dispatcher.PushFrameImpl(DispatcherFrame frame) at System.Windows.Threading.Dispatcher.PushFrame(DispatcherFrame frame) at System.Windows.Threading.Dispatcher.Run() at System.Windows.Application.RunDispatcher(Object ignore) at System.Windows.Application.RunInternal(Window window) at System.Windows.Application.Run(Window window) at System.Windows.Application.Run() at FsDocumentationBuilder.App.Main() in D:\Users\dcveeneman\Documents\Visual Studio 2010\Projects\FsDocumentationBuilder\FsDocumentationBuilder\obj\x86\Debug\App.g.cs:line 50 at System.AppDomain._nExecuteAssembly(RuntimeAssembly assembly, String[] args) at System.AppDomain.ExecuteAssembly(String assemblyFile, Evidence assemblySecurity, String[] args) at Microsoft.VisualStudio.HostingProcess.HostProc.RunUsersAssembly() at System.Threading.ThreadHelper.ThreadStart_Context(Object state) at System.Threading.ExecutionContext.Run(ExecutionContext executionContext, ContextCallback callback, Object state, Boolean ignoreSyncCtx) at System.Threading.ExecutionContext.Run(ExecutionContext executionContext, ContextCallback callback, Object state) at System.Threading.ThreadHelper.ThreadStart() InnerException: System.Data.EntityCommandCompilationException Message=An error occurred while preparing the command definition. See the inner exception for details. Source=System.Data.Entity StackTrace: at System.Data.Mapping.Update.Internal.UpdateTranslator.CreateCommand(DbModificationCommandTree commandTree) at System.Data.Mapping.Update.Internal.DynamicUpdateCommand.CreateCommand(UpdateTranslator translator, Dictionary`2 identifierValues) at System.Data.Mapping.Update.Internal.DynamicUpdateCommand.Execute(UpdateTranslator translator, EntityConnection connection, Dictionary`2 identifierValues, List`1 generatedValues) at System.Data.Mapping.Update.Internal.UpdateTranslator.Update(IEntityStateManager stateManager, IEntityAdapter adapter) InnerException: System.NotSupportedException Message=Server-generated keys and server-generated values are not supported by SQL Server Compact. Source=System.Data.SqlServerCe.Entity StackTrace: at System.Data.SqlServerCe.SqlGen.DmlSqlGenerator.GenerateReturningSql(StringBuilder commandText, DbModificationCommandTree tree, ExpressionTranslator translator, DbExpression returning) at System.Data.SqlServerCe.SqlGen.DmlSqlGenerator.GenerateInsertSql(DbInsertCommandTree tree, List`1& parameters, Boolean isLocalProvider) at System.Data.SqlServerCe.SqlGen.SqlGenerator.GenerateSql(DbCommandTree tree, List`1& parameters, CommandType& commandType, Boolean isLocalProvider) at System.Data.SqlServerCe.SqlCeProviderServices.CreateCommand(DbProviderManifest providerManifest, DbCommandTree commandTree) at System.Data.SqlServerCe.SqlCeProviderServices.CreateDbCommandDefinition(DbProviderManifest providerManifest, DbCommandTree commandTree) at System.Data.Common.DbProviderServices.CreateCommandDefinition(DbCommandTree commandTree) at System.Data.Common.DbProviderServices.CreateCommand(DbCommandTree commandTree) at System.Data.Mapping.Update.Internal.UpdateTranslator.CreateCommand(DbModificationCommandTree commandTree) InnerException:

    Read the article

  • Does WPF break an Entity Framework ObjectContext?

    - by David Veeneman
    I am getting started with Entity Framework 4, and I am getting ready to write a WPF demo app to learn EF4 better. My LINQ queries return IQueryable<T>, and I know I can drop those into an ObservableCollection<T> with the following code: IQueryable<Foo> fooList = from f in Foo orderby f.Title select f; var observableFooList = new ObservableCollection<Foo>(fooList); At that point, I can set the appropriate property on my view model to the observable collection, and I will get WPF data binding between the view and the view model property. Here is my question: Do I break the ObjectContext when I move my foo list to the observable collection? Or put another way, assuming I am otherwise handling my ObjectContext properly, will EF4 properly update the model (and the database)? The reason why I ask is this: NHibernate tracks objects at the collection level. If I move an NHibernate IList<T> to an observable collection, it breaks NHibernate's change tracking mechanism. That means I have to do some very complicated object wrapping to get NHibernate to work with WPF. I am looking at EF4 as a way to dispense with all that. So, to get EF4 working with WPF, is it as simple as dropping my IQueryable<T> results into an ObservableCollection<T>. Does that preserve change-tracking on my EDM entity objects? Thanks for your help.

    Read the article

  • ADO.net, Check if ObjectContext is writeable

    - by user287107
    I have an embedded database in an asp.net mvc project. If I try to write to the file, I sometimes get a write failed exception because the SQL Server can't write to the file. How can I check an ObjectContext, if its writeable, without actually writing something to the database?

    Read the article

  • Retrieving/Updating Entity Framework POCO objects that already exist in the ObjectContext

    - by jslatts
    I have a project using Entity Framework 4.0 with POCOs (data is stored in SQL DB, lazyloading is enabled) as follows: public class ParentObject { public int ID {get; set;} public virtual List<ChildObject> children {get; set;} } public class ChildObject { public int ID {get; set;} public int ChildRoleID {get; set;} public int ParentID {get; set;} public virtual ParentObject Parent {get; set;} public virtual ChildRoleObject ChildRole {get; set;} } public class ChildRoleObject { public int ID {get; set;} public string Name {get; set;} public virtual List<ChildObject> children {get; set;} } I want to create a new ChildObject, assign it a role, then add it to an existing ParentObject. Afterwards, I want to send the new ChildObject to the caller. The code below works fine until it tries to get the object back from the database. The newChildObjectInstance only has the ChildRoleID set and does not contain a reference to the actual ChildRole object. I try and pull the new instance back out of the database in order to populate the ChildRole property. Unfortunately, in this case, instead of creating a new instance of ChildObject and assigning it to retreivedChildObject, EF finds the existing ChildObject in the context and returns the in-memory instance, with a null ChildRole property. public ChildObject CreateNewChild(int id, int roleID) { SomeObjectContext myRepository = new SomeObjectContext(); ParentObject parentObjectInstance = myRepository.GetParentObject(id); ChildObject newChildObjectInstance = new ChildObject() { ParentObject = parentObjectInstance, ParentID = parentObjectInstance.ID, ChildRoleID = roleID }; parentObjectInstance.children.Add(newChildObjectInstance); myRepository.Save(); ChildObject retreivedChildObject = myRepository.GetChildObject(newChildObjectInstance.ID); string assignedRoleName = retreivedChildObject.ChildRole.Name; //Throws exception, ChildRole is null return retreivedChildObject; } I have tried setting MergeOptions to Overwrite, calling ObjectContext.Refresh() and ObjectContext.DetectChanges() to no avail... I suspect this is related to the proxy objects that EF injects when working with POCOs. Has anyone run into this issue before? If so, what was the solution?

    Read the article

  • Why is ExecuteFunction method only available through base.ExecuteFunction in a child class of Object

    - by Matt
    I'm trying to call ObjectContext.ExecuteFunction from my objectcontext object in the repository of my site. The repository is generic, so all I have is an ObjectContext object, rather than one that actually represents my specific one from the Entity Framework. Here's an example of code that was generated that uses the ExecuteFunction method: [global::System.CodeDom.Compiler.GeneratedCode("System.Data.Entity.Design.EntityClassGenerator", "4.0.0.0")] public global::System.Data.Objects.ObjectResult<ArtistSearchVariation> FindSearchVariation(string source) { global::System.Data.Objects.ObjectParameter sourceParameter; if ((source != null)) { sourceParameter = new global::System.Data.Objects.ObjectParameter("Source", source); } else { sourceParameter = new global::System.Data.Objects.ObjectParameter("Source", typeof(string)); } return base.ExecuteFunction<ArtistSearchVariation>("FindSearchVariation", sourceParameter); } But what I would like to do is something like this... public class Repository<E, C> : IRepository<E, C>, IDisposable where E : EntityObject where C : ObjectContext { private readonly C _ctx; // ... public ObjectResult<E> ExecuteFunction(string functionName, params[]) { // Create object parameters return _ctx.ExecuteFunction<E>(functionName, /* parameters */) } } Anyone know why I have to call ExecuteFunction from base instead of _ctx? Also, is there any way to do something like I've written out? I would really like to keep my repository generic, but with having to execute stored procedures it's looking more and more difficult... Thanks, Matt

    Read the article

  • ObjectContext ConnectionString Sqlite

    - by codegarten
    I need to connect to a database in Sqlite so i downloaded and installed System.Data.SQLite and with the designer dragged all my tables. The designer created a .cs file with public class Entities : ObjectContext and 3 constructors: 1st public Entities() : base("name=Entities", "Entities") this one load the connection string from App.config and works fine. App.config <connectionStrings> <add name="Entities" connectionString="metadata=res://*/Db.TracModel.csdl|res://*/Db.TracModel.ssdl|res://*/Db.TracModel.msl;provider=System.Data.SQLite;provider connection string=&quot;data source=C:\Users\Filipe\Desktop\trac.db&quot;" providerName="System.Data.EntityClient" /> </connectionStrings> 2nd public Entities(string connectionString) : base(connectionString, "Entities") 3rd public Entities(EntityConnection connection) : base(connection, "Entities") Here is the problem, i already tried n configuration, already used EntityConnectionStringBuilder to make the connection string with no luck. Can you please point me in the right direction!? EDIT(1) How can i construct a valid connection string?!

    Read the article

  • Organizing Eager Queries in an ObjectContext

    - by Nix
    I am messing around with Entity Framework 3.5 SP1 and I am trying to find a cleaner way to do the below. I have an EF model and I am adding some Eager Loaded entities and i want them all to reside in the "Eager" property in the context. We originally were just changing the entity set name, but it seems a lot cleaner to just use a property, and keep the entity set name in tact. Example: Context - EntityType - AnotherType - Eager (all of these would have .Includes to pull in all assoc. tables) - EntityType - AnotherType Currently I am using composition but I feel like there is an easier way to do what I want. namespace Entities{ public partial class TestObjectContext { EagerExtensions Eager { get;set;} public TestObjectContext(){ Eager = new EagerExtensions (this); } } public partial class EagerExtensions { TestObjectContext context; public EagerExtensions(TestObjectContext _context){ context = _context; } public IQueryable<TestEntity> TestEntity { get { return context.TestEntity .Include("TestEntityType") .Include("Test.Attached.AttachedType") .AsQueryable(); } } } } public class Tester{ public void ShowHowIWantIt(){ TestObjectContext context= new TestObjectContext(); var query = from a in context.Eager.TestEntity select a; } }

    Read the article

  • EF4 + STE: Reattaching via a WCF Service? Using a new objectcontext each and every time?

    - by Martin
    Hi there, I am planning to use WCF (not ria) in conjunction with Entity Framework 4 and STE (Self tracking entitites). If i understnad this correctly my WCF should return an entity or collection of entities (using LIST for example and not IQueryable) to the client (in my case silverlight) The client then can change the entity or update it. At this point i believe it is self tracking???? This is where i sort of get a bit confused as there are a lot of reported problems with STEs not tracking.. Anyway... Then to update i just need to send back the entity to my WCF service on another method to do the update. I should be creating a new OBJECTCONTEXT everytime? In every method? If i am creaitng a new objectcontext everytime in everymethod on my WCF then don't i need to re-attach the STE to the objectcontext? So basically this alone wouldn't work?? using(var ctx = new MyContext()) { ctx.Orders.ApplyChanges(order); ctx.SaveChanges(); } Or should i be creating the object context once in the constructor of the WCF service so that 1 call and every additional call using the same wcf instance uses the same objectcontext? I could create and destroy the wcf service in each method call from the client - hence creating in effect a new objectcontext each time. I understand that it isn't a good idea to keep the objectcontext alive for very long. Any insight or information would be gratefully appreciated thanks

    Read the article

  • Unable to use stored procs in a generic repository for the entity framework. (ASP.NET MVC 2)

    - by Matt
    Hi, I have a generic repository that uses the entity framework to manipulate the database. The original code is credited to Morshed Anwar's post on CodeProject. I've taken his code and modified is slightly to fit my needs. Unfortunately I'm unable to call an Imported Function because the function is only recognized for my specific instance of the entity framework public class Repository<E, C> : IRepository<E, C>, IDisposable where E : EntityObject where C : ObjectContext { private readonly C _ctx; public ObjectResult<MyObject> CallFunction() { // This does not work because "CallSomeImportedFunction" only works on // My object. I also cannot cast it (TrackItDBEntities)_ctx.CallSomeImportedFunction(); // Not really sure why though... but either way that kind of ruins the genericness off it. return _ctx.CallSomeImportedFunction(); } } Anyone know how I can make this work with the repository I already have? Or does anyone know a generic way of calling stored procedures with entity framework? Thanks, Matt

    Read the article

  • Is it possible to store ObjectContext on the client when using WCF and Entity Framework?

    - by Sergey
    Hello, I have a WCF service which performs CRUD operation on my data model: Add, Get, Update and Delete. And I'm using Entity Framework for my data model. On the other side there is a client application which calls methods of the WCF service. For example I have a Customer class: [DataContract] public class Customer { public Guid CustomerId {get; set;} public string CustomerName {get; set;} } and WCF service defines this method: public void AddCustomer(Customer c) { MyEntities _entities = new MyEntities(); _entities.AddToCustomers(c); _entities.SaveChanges(); } and the client application passes objects to the WCF service: var customer = new Customer(){CustomerId = Guid.NewGuid, CustomerName="SomeName"}; MyService svc = new MyService(); svc.Add(customer); // or svc.Update(customer) for example But when I need to pass a great amount of objects to the WCF it could be a perfomance issue because of I need to create ObjectContext each time when I'm doing Add(), Update(), Get() or Delete(). What I'm thinking on is to keep ObjectContext on the client and pass ObjectContext to the wcf methods as additional parameter. Is it possible to create and keep ObjectContext on the client and don't recreate it for each operation? If it is not, how could speed up the passing of huge amount of data to the wcf service? Sergey

    Read the article

  • 3 methods for adding a "Product" through Entity Framework. What's the difference?

    - by Kohan
    Reading this MSDN article titled "Working with ObjectSet (Entity Framework)" It shows two examples on how to add a Product.. one for 3.5 and another for 4.0. http://msdn.microsoft.com/en-us/library/ee473442.aspx Through my lack of knowledge I am possibly completely missing something here, but i never added a Product like this: //In .NET Framework 3.5 SP1, use the following code: (ObjectQuery) using (AdventureWorksEntities context = new AdventureWorksEntities()) { // Add the new object to the context. context.AddObject("Products", newProduct); } //New in .NET Framework 4, use the following code: (ObjectSet) using (AdventureWorksEntities context = new AdventureWorksEntities()) { // Add the new object to the context. context.Products.AddObject(newProduct); } I would not have done it either way and just used: // (My familiar way) using (AdventureWorksEntities context = new AdventureWorksEntities()) { // Add the new object to the context. context.AddToProducts(newProduct); } What's the difference between these three ways? Is "My way" just another way of using an ObjectQuery? Thanks, Kohan

    Read the article

1 2 3 4 5 6 7  | Next Page >