Search Results

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

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

  • How to pass multiple parameter in DomainService - WCF

    - by S.Amani
    Hi, Let's say I have a window which should submit 3 model in client side (Silverlight Client Application). My problem is each time I submit the form, data on the server side which I passed them from client are empty. I've used nested class which contains my models, instead of passing multiple object as parameter, but it didn't work again. My Personnel Data Transfer Object Code is something like this : [DataContract] public class PersonnelDTO : EntityObject { [Key] [DataMember] public int PersonnelId { get; set; } [Include] [DataMember] [Association("Personnel_ID", "PersonnelId", "Personnel_ID")] public Personnel Personnel { get; set; } [Include] [DataMember] [Association("Personnel_Info_ID", "PersonnelId", "Personnel_Info_ID")] public Personnel_Info PersonnelInfo { get; set; } } I fill up this model to pass data from client to server (DomainService). and also my domain service code is : [Invoke] public void AddPersonnel(PersonnelDTO personnelDTO) { // Model are EMPTY in DTO ObjectContext.AddToPersonnels(personnelDTO.Personnel); ObjectContext.AddToPersonnel_Info(personnelDTO.PersonnelInfo); ObjectContext.SaveChanges(); } I don't know if there is a way to pass multiple parameter in WCF Service method include Generic List. Any advice will be graceful. Thanks.

    Read the article

  • Way to automate setting of MergeOptions

    - by Nix
    I am looking for an automated way to iterate over all ObjectQueries and set the merge option to no tracking (read only context). Once i find out how to do it i will be able to generate a default read only context using a T4 template. Is this possible? For example lets say i have these tables in my object context SampleContext TableA TableB TableC I would have to go through and do the below. SampleContext sc = new SampleContext(); sc.TableA.MergeOption = MergeOption.NoTracking; sc.TableB.MergeOption = MergeOption.NoTracking; sc.TableC.MergeOption = MergeOption.NoTracking; I am trying to find a way to generalize this using object context. I want to get it down to something like foreach(var objectQuery : sc){ objectQuery.MergeOption = MergeOption.NoTracking; } Preferably I would like to do it using the baseclass(ObjectContext): ObjectContext baseClass = sc as ObjectContext var objectQueries = sc.MetadataWorkspace.GetItem("Magic Object Query Option); But i am not sure i can even get access to the queries. Any help would be appreciated.

    Read the article

  • Should I remove all inheritance from my model in order to work with ria services?

    - by TimothyP
    I've posted some questions on this before, but it's different. So consider a small portion of our model: Person Customer Employee Spouse Person is the base class which has 3 classes that inherit from it. These 4 are very central in our design and link to many other entities. I could solve all the problems I'm experiencing with ria-services by removing the inheritance but that would really increase the complexety of the model. The first problem I experienced was that I couldn't query for Customers, Employees or Spouses, but someone gave me a solution, which was to add something like this to the DomainService: public IQueryable<Employee> GetEmployees() { return this.ObjectContext.People.OfType<Employee>(); } public IQueryable<Customer> GetCustomers() { return this.ObjectContext.People.OfType<Customer>(); } public IQueryable<Spouse> GetSpouses() { return this.ObjectContext.People.OfType<Spouse>(); } Next I tried something that seemed very normal to me: var employee = new Employee() { //.... left out to reduce the length of this question }; var spouse = new Spouse() { //.... left out to reduce the length of this questions }; employee.Spouse = spouse; context.People.Add(spouse); context.People.Add(employee); context.SubmitChanges(); Then I get the following exception: Cannot retrieve an entity set for the derived entity type 'Spouse'. Use EntityContainer.GetEntitySet(Type) to get the entity set for the base entity type 'Person'. Even when the spouse is already in the database, and I retreive it first I get similar exceptions. Also note that for some reason in some places "Persons" is used instead of "People"... So how do I solve this problem, what am I doing wrong and will I keep running into walls when using ria services with inheritance? I found some references on the web, all saying it works and then some DomainService code in which they suposedly changed something but no details... I'm using VS2010 RC1 + Silveright 4

    Read the article

  • How to Access a descendant object's internal method in C#

    - by Giovanni Galbo
    I'm trying to access a method that is marked as internal in the parent class (in its own assembly) in an object that inherits from the same parent. Let me explain what I'm trying to do... I want to create Service classes that return IEnumberable with an underlying List to non-Service classes (e.g. the UI) and optionally return an IEnumerable with an underlying IQueryable to other services. I wrote some sample code to demonstrate what I'm trying to accomplish, shown below. The example is not real life, so please remember that when commenting. All services would inherit from something like this (only relevant code shown): public class ServiceBase<T> { protected readonly ObjectContext _context; protected string _setName = String.Empty; public ServiceBase(ObjectContext context) { _context = context; } public IEnumerable<T> GetAll() { return GetAll(false); } //These are not the correct access modifiers.. I want something //that is accessible to children classes AND between descendant classes internal protected IEnumerable<T> GetAll(bool returnQueryable) { var query = _context.CreateQuery<T>(GetSetName()); if(returnQueryable) { return query; } else { return query.ToList(); } } private string GetSetName() { //Some code... return _setName; } } Inherited services would look like this: public class EmployeeService : ServiceBase<Employees> { public EmployeeService(ObjectContext context) : base(context) { } } public class DepartmentService : ServiceBase<Departments> { private readonly EmployeeService _employeeService; public DepartmentService(ObjectContext context, EmployeeService employeeService) : base(context) { _employeeService = employeeService; } public IList<Departments> DoSomethingWithEmployees(string lastName) { //won't work because method with this signature is not visible to this class var emps = _employeeService.GetAll(true); //more code... } } Because the parent class lives is reusable, it would live in a different assembly than the child services. With GetAll(bool returnQueryable) being marked internal, the children would not be able to see each other's GetAll(bool) method, just the public GetAll() method. I know that I can add a new internal GetAll method to each service (or perhaps an intermediary parent class within the same assembly) so that each child service within the assembly can see each other's method; but it seems unnecessary since the functionality is already available in the parent class. For example: internal IEnumerable<Employees> GetAll(bool returnIQueryable) { return base.GetAll(returnIQueryable); } Essentially what I want is for services to be able to access other service methods as IQueryable so that they can further refine the uncommitted results, while everyone else gets plain old lists. Any ideas? EDIT You know what, I had some fun playing a little code golf with this... but ultimately I wouldn't be able to use this scheme anyway because I pass interfaces around, not classes. So in my example GetAll(bool returnIQueryable) would not be in the interface, meaning I'd have to do casting, which goes against what I'm trying to accomplish. I'm not sure if I had a brain fart or if I was just too excited trying to get something that I thought was neat to work. Either way, thanks for the responses.

    Read the article

  • Entity Framework 4 relationship management in POCO Templates - More lazy than FixupCollection?

    - by Joe Wood
    I've been taking a look at EF4 POCO templates in beta 2. The FixupCollection looks fine for maintaining the model correctness after updating the relationship collection property (i.e. product.Orders it would set the order.Product reference ). But what about support for handling the scenario when some of those Order objects are removed from the context? The use-case of maintaining cascading deletes in the in-memory model. The old Typed DataSet model used to do this by performing the query through the container to derive the relationship results. Like the DataSet, this would require a reference to the ObjectContext inside the entity class so that it could query the top-level Order collection. Better support for Separation of Concerns in the ObjectContext would be required. It looks like EF is not suited to this use-case that DataSets did out of the box.... am I right?

    Read the article

  • UDF call in entity framework is cached

    - by Fred Yang
    I am doing a test after reading an article http://blogs.msdn.com/alexj/archive/2009/08/07/tip-30-how-to-use-a-custom-store-function.aspx about udf function called. When I use a function with objectContext.Entities.Where( t= udf(para1, para2) == 1), here the Entities is not ObjectQuery, but an ObjectSet, the first time I call the method, it runs correctly, if I reuse the objectContext,and run it again but with different para1, para2, then the previous parameter values still cached, and the result is same as previous one, which is wrong. The sql profiler shows that both query hit the database, but the t-sql is the same. Am I missing something? And the ObjectSet does not support .where(esql_string). How to get udf working with ObjectSet? Thanks Fred

    Read the article

  • L2E delete exception

    - by 5YrsLaterDBA
    I have following code to delete an user from database: try { var user = from u in db.Users where u.Username == username select u; if (user.Count() > 0) { db.DeleteObject(user.First()); db.SaveChanges(); } } but I got exception like this: 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(Boolean acceptChangesDuringSave) at System.Data.Objects.ObjectContext.SaveChanges() at MyCompany.SystemSoftware.DQMgr.User.DeleteUser(String username) in C:\workspace\SystemSoftware\SystemSoftware\src\dqm\User.cs:line 479 The Users table is referenced by few other tables. It is probably caused by the foreign key constraint?

    Read the article

  • RIA Services Repository Save does not work!?

    - by Savvas Sopiadis
    Hello everybody! Doing my first SL4 MVVM RIA based application and i ran into the following situation: updating a record (EF4,NO-POCOS!!) in the SL-client seems to take place, but values in the dbms are unchanged. Debugging with Fiddler the message on save is (amongst others): EntityActions.nil? b9http://schemas.microsoft.com/2003/10/Serialization/Arrays^HasMemberChanges?^Id?^ Operation?Update I assume that this says only: hey! the dbms should do an update on this record, AND nothing more! Is that right?! I 'm using a generic repository like this: public class Repository<T> : IRepository<T> where T : class { IObjectSet<T> _objectSet; IObjectContext _objectContext; public Repository(IObjectContext objectContext) { this._objectContext = objectContext; _objectSet = objectContext.CreateObjectSet<T>(); } public IQueryable<T> AsQueryable() { return _objectSet; } public IEnumerable<T> GetAll() { return _objectSet.ToList(); } public IEnumerable<T> Find(Expression<Func<T, bool>> where) { return _objectSet.Where(where); } public T Single(Expression<Func<T, bool>> where) { return _objectSet.Single(where); } public T First(Expression<Func<T, bool>> where) { return _objectSet.First(where); } public void Delete(T entity) { _objectSet.DeleteObject(entity); } public void Add(T entity) { _objectSet.AddObject(entity); } public void Attach(T entity) { _objectSet.Attach(entity); } public void Save() { _objectContext.SaveChanges(); } } The DomainService Update Method is the following: [Update] public void UpdateCulture(Culture currentCulture) { if (currentCulture.EntityState == System.Data.EntityState.Detached) { this.cultureRepository.Attach(currentCulture); } this.cultureRepository.Save(); } I know that the currentCulture-Entity is detached. What confuses me (amongst other things) is this: is the _objectContext still alive? (which means it "will be"??? aware of the changes made to record, so simply calling Attach() and then Save() should be enough!?!?) What am i missing? Development Environment: VS2010RC - Entity Framework 4 (no POCOs) Thanks in advance

    Read the article

  • TryGetObjectByKey... empty ObjectSets

    - by Rickjaah
    When I use TryGetObjectByKey on my ObjectContext, it returns an error. An item with a duplicate value already exists. When I look at my objectContext, I see that the ObjectSets are empty. What Am I doing wrong... When I enumerate the ObjectSet by hand, by using ToArray on it, or by using the debugger, it does work. LazyLoadingEnabled = true. I reuse 2 tables from another EDMX, but they are in different namespaces and they are not the objectSets i try to approach.

    Read the article

  • POCO inherited type could not pass addObject method

    - by bryanevil
    Hi all I am using a POCO class name "Company" generate from the T4 POCO code generator to create a derived class - name "CompanyBO" by "public class CompanyBO:Company", but when i call addObject method: public void Delete(T entity) { CustomerWebPortalEntities entities = new CustomerWebPortalEntities(); entities.AddObject(entity.GetType().BaseType.Name, entity); entities.DeleteObject(entity); SaveChanges(); } it compliant this: The EntitySet name 'CustomerWebPortalEntities.Company' could not be found. System.Data.Objects.ObjectContext.GetEntitySet(String entitySetName, String entityContainerName) at System.Data.Objects.ObjectContext.GetEntitySetFromName(String entitySetName) Could you please tell me whats going wrong here? How do I resolve this problem? Best Regards Bryan

    Read the article

  • Can't Use Generic C# Class in Using Statement

    - by Eric J.
    I'm trying to use a generic class in a using statement but the compiler can't seem to treat it as implementing IDisposable. using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Data.Objects; namespace Sandbox { public sealed class UnitOfWorkScope<T> where T : ObjectContext, IDisposable, new() { public void Dispose() { } } public class MyObjectContext : ObjectContext, IDisposable { public MyObjectContext() : base("DummyConnectionString") { } #region IDisposable Members void IDisposable.Dispose() { throw new NotImplementedException(); } #endregion } public class Consumer { public void DoSomething() { using (new UnitOfWorkScope<MyObjectContext>()) { } } } } Compiler error is: Error 1 'Sandbox.UnitOfWorkScope<Sandbox.MyObjectContext>': type used in a using statement must be implicitly convertible to 'System.IDisposable' I implemented IDisposable on UnitOfWorkScope (and to see if that was the problem, also on MyObjectContext). What am I missing?

    Read the article

  • How to create multiple Repository object inside a Repository class using Unit Of Work?

    - by Santosh
    I am newbie to MVC3 application development, currently, we need following Application technologies as requirement MVC3 framework IOC framework – Autofac to manage object creation dynamically Moq – Unit testing Entity Framework Repository and Unit Of Work Pattern of Model class I have gone through many article to explore an basic idea about the above points but still I am little bit confused on the “Repository and Unit Of Work Pattern “. Basically what I understand Unit Of Work is a pattern which will be followed along with Repository Pattern in order to share the single DB Context among all Repository object, So here is my design : IUnitOfWork.cs public interface IUnitOfWork : IDisposable { IPermitRepository Permit_Repository{ get; } IRebateRepository Rebate_Repository { get; } IBuildingTypeRepository BuildingType_Repository { get; } IEEProjectRepository EEProject_Repository { get; } IRebateLookupRepository RebateLookup_Repository { get; } IEEProjectTypeRepository EEProjectType_Repository { get; } void Save(); } UnitOfWork.cs public class UnitOfWork : IUnitOfWork { #region Private Members private readonly CEEPMSEntities context = new CEEPMSEntities(); private IPermitRepository permit_Repository; private IRebateRepository rebate_Repository; private IBuildingTypeRepository buildingType_Repository; private IEEProjectRepository eeProject_Repository; private IRebateLookupRepository rebateLookup_Repository; private IEEProjectTypeRepository eeProjectType_Repository; #endregion #region IUnitOfWork Implemenation public IPermitRepository Permit_Repository { get { if (this.permit_Repository == null) { this.permit_Repository = new PermitRepository(context); } return permit_Repository; } } public IRebateRepository Rebate_Repository { get { if (this.rebate_Repository == null) { this.rebate_Repository = new RebateRepository(context); } return rebate_Repository; } } } PermitRepository .cs public class PermitRepository : IPermitRepository { #region Private Members private CEEPMSEntities objectContext = null; private IObjectSet<Permit> objectSet = null; #endregion #region Constructors public PermitRepository() { } public PermitRepository(CEEPMSEntities _objectContext) { this.objectContext = _objectContext; this.objectSet = objectContext.CreateObjectSet<Permit>(); } #endregion public IEnumerable<RebateViewModel> GetRebatesByPermitId(int _permitId) { // need to implment } } PermitController .cs public class PermitController : Controller { #region Private Members IUnitOfWork CEEPMSContext = null; #endregion #region Constructors public PermitController(IUnitOfWork _CEEPMSContext) { if (_CEEPMSContext == null) { throw new ArgumentNullException("Object can not be null"); } CEEPMSContext = _CEEPMSContext; } #endregion } So here I am wondering how to generate a new Repository for example “TestRepository.cs” using same pattern where I can create more then one Repository object like RebateRepository rebateRepo = new RebateRepository () AddressRepository addressRepo = new AddressRepository() because , what ever Repository object I want to create I need an object of UnitOfWork first as implmented in the PermitController class. So if I would follow the same in each individual Repository class that would again break the priciple of Unit Of Work and create multiple instance of object context. So any idea or suggestion will be highly appreciated. Thank you

    Read the article

  • How to use LINQ To Entities for filtering when many methods are not supported?

    - by Kinderchocolate
    Hi, I have a table in SQL database: ID Data Value 1 1 0.1 1 2 0.4 2 10 0.3 2 11 0.2 3 10 0.5 3 11 0.6 For each unique value in Data, I want to filter out the row with the largest ID. For example: In the table above, I want to filter out the third and fourth row because the fifth and sixth rows have the same Data values but their IDs (3) are larger (2 in the third and fourth row). I tried this in Linq to Entities: IQueryable<DerivedRate> test = ObjectContext.DerivedRates.OrderBy(d => d.Data).ThenBy(d => d.ID).SkipWhile((d, index) => (index == size - 1) || (d.ID != ObjectContext.DerivedRates.ElementAt(index + 1).ID)); Basically, I am sorting the list and removing the duplicates by checking if the next element has an identical ID. However, this doesn't work because SkipWhile(index) and ElementAt(index) aren't supported in Linq to Entities. I don't want to pull the entire gigantic table into an array before sorting it. Is there a way?

    Read the article

  • Are elements returned by Linq-to-Entities query streamed from the DB one at the time or are they retrieved all at once?

    - by carewithl
    Are elements returned by Linq-to-Entities query streamed from the database one at the time ( as they are requested ) or are they retrieved all at once: SampleContext context = new SampleContext(); // SampleContext derives from ObjectContext var search = context.Contacts; foreach (var contact in search) { Console.WriteLine(contact.ContactID); // is each Contact retrieved from the DB // only when foreach requests it? } thank you in advance

    Read the article

  • Entity Framework version 1- Brief Synopsis and Tips &ndash; Part 1

    - by Rohit Gupta
    To Do Eager loading use Projections (for e.g. from c in context.Contacts select c, c.Addresses)  or use Include Query Builder Methods (Include(“Addresses”)) If there is multi-level hierarchical Data then to eager load all the relationships use Include Query Builder methods like customers.Include("Order.OrderDetail") to include Order and OrderDetail collections or use customers.Include("Order.OrderDetail.Location") to include all Order, OrderDetail and location collections with a single include statement =========================================================================== If the query uses Joins then Include() Query Builder method will be ignored, use Nested Queries instead If the query does projections then Include() Query Builder method will be ignored Use Address.ContactReference.Load() OR Contact.Addresses.Load() if you need to Deferred Load Specific Entity – This will result in extra round trips to the database ObjectQuery<> cannot return anonymous types... it will return a ObjectQuery<DBDataRecord> Only Include method can be added to Linq Query Methods Any Linq Query method can be added to Query Builder methods. If you need to append a Query Builder Method (other than Include) after a LINQ method  then cast the IQueryable<Contact> to ObjectQuery<Contact> and then append the Query Builder method to it =========================================================================== Query Builder methods are Select, Where, Include Methods which use Entity SQL as parameters e.g. "it.StartDate, it.EndDate" When Query Builder methods do projection then they return ObjectQuery<DBDataRecord>, thus to iterate over this collection use contact.Item[“Name”].ToString() When Linq To Entities methods do projection, they return collection of anonymous types --- thus the collection is strongly typed and supports Intellisense EF Object Context can track changes only on Entities, not on Anonymous types. If you use a Defining Query for a EntitySet then the EntitySet becomes readonly since a Defining Query is the same as a View (which is treated as a ReadOnly by default). However if you want to use this EntitySet for insert/update/deletes then we need to map stored procs (as created in the DB) to the insert/update/delete functions of the Entity in the Designer You can use either Execute method or ToList() method to bind data to datasources/bindingsources If you use the Execute Method then remember that you can traverse through the ObjectResult<> collection (returned by Execute) only ONCE. In WPF use ObservableCollection to bind to data sources , for keeping track of changes and letting EF send updates to the DB automatically. Use Extension Methods to add logic to Entities. For e.g. create extension methods for the EntityObject class. Create a method in ObjectContext Partial class and pass the entity as a parameter, then call this method as desired from within each entity. ================================================================ DefiningQueries and Stored Procedures: For Custom Entities, one can use DefiningQuery or Stored Procedures. Thus the Custom Entity Collection will be populated using the DefiningQuery (of the EntitySet) or the Sproc. If you use Sproc to populate the EntityCollection then the query execution is immediate and this execution happens on the Server side and any filters applied will be applied in the Client App. If we use a DefiningQuery then these queries are composable, meaning the filters (if applied to the entityset) will all be sent together as a single query to the DB, returning only filtered results. If the sproc returns results that cannot be mapped to existing entity, then we first create the Entity/EntitySet in the CSDL using Designer, then create a dummy Entity/EntitySet using XML in the SSDL. When creating a EntitySet in the SSDL for this dummy entity, use a TSQL that does not return any results, but does return the relevant columns e.g. select ContactID, FirstName, LastName from dbo.Contact where 1=2 Also insure that the Entity created in the SSDL uses the SQL DataTypes and not .NET DataTypes. If you are unable to open the EDMX file in the designer then note the Errors ... they will give precise info on what is wrong. The Thrid option is to simply create a Native Query in the SSDL using <Function Name="PaymentsforContact" IsComposable="false">   <CommandText>SELECT ActivityId, Activity AS ActivityName, ImagePath, Category FROM dbo.Activities </CommandText></FuncTion> Then map this Function to a existing Entity. This is a quick way to get a custom Entity which is regular Entity with renamed columns or additional columns (which are computed columns). The disadvantage to using this is that It will return all the rows from the Defining query and any filter (if defined) will be applied only at the Client side (after getting all the rows from DB). If you you DefiningQuery instead then we can use that as a Composable Query. The Fourth option (for mapping a READ stored proc results to a non-existent Entity) is to create a View in the Database which returns all the fields that the sproc also returns, then update the Model so that the model contains this View as a Entity. Then map the Read Sproc to this View Entity. The other option would be to simply create the View and remove the sproc altogether. ================================================================ To Execute a SProc that does not return a entity, use a EntityCommand to execute that proc. You cannot call a sproc FunctionImport that does not return Entities From Code, the only way is to use SSDL function calls using EntityCommand.  This changes with EntityFramework Version 4 where you can return Scalar Types, Complex Types, Entities or NonQuery ================================================================ UDF when created as a Function in SSDL, we need to set the Name & IsComposable properties for the Function element. IsComposable is always false for Sprocs, for UDF's set this to true. You cannot call UDF "Function" from within code since you cannot import a UDF Function into the CSDL Model (with Version 1 of EF). only stored procedures can be imported and then mapped to a entity ================================================================ Entity Framework requires properties that are involved in association mappings to be mapped in all of the function mappings for the entity (Insert, Update and Delete). Because Payment has an association to Reservation... hence we need to pass both the paymentId and reservationId to the Delete sproc even though just the paymentId is the PK on the Payment Table. ================================================================ When mapping insert, update and delete procs to a Entity, insure that all the three or none are mapped. Further if you have a base class and derived class in the CSDL, then you must map (ins, upd, del) sprocs to all parent and child entities in the inheritance relationship. Note that this limitation that base and derived entity methods must all must be mapped does not apply when you are mapping Read Stored Procedures.... ================================================================ You can write stored procedures SQL directly into the SSDL by creating a Function element in the SSDL and then once created, you can map this Function to a CSDL Entity directly in the designer during Function Import ================================================================ You can do Entity Splitting such that One Entity maps to multiple tables in the DB. For e.g. the Customer Entity currently derives from Contact Entity...in addition it also references the ContactPersonalInfo Entity. One can copy all properties from the ContactPersonalInfo Entity into the Customer Entity and then Delete the CustomerPersonalInfo entity, finall one needs to map the copied properties to the ContactPersonalInfo Table in Table Mapping (by adding another table (ContactPersonalInfo) to the Table Mapping... this is called Entity Splitting. Thus now when you insert a Customer record, it will automatically create SQL to insert records into the Contact, Customers and ContactPersonalInfo tables even though you have a Single Entity called Customer in the CSDL =================================================================== There is Table by Type Inheritance where another EDM Entity can derive from another EDM entity and absorb the inherted entities properties, for example in the Break Away Geek Adventures EDM, the Customer entity derives (inherits) from the Contact Entity and absorbs all the properties of Contact entity. Thus when you create a Customer Entity in Code and then call context.SaveChanges the Object Context will first create the TSQL to insert into the Contact Table followed by a TSQL to insert into the Customer table =================================================================== Then there is the Table per Hierarchy Inheritance..... where different types are created based on a condition (similar applying a condition to filter a Entity to contain filtered records)... the diference being that the filter condition populates a new Entity Type (derived from the base Entity). In the BreakAway sample the example is Lodging Entity which is a Abstract Entity and Then Resort and NonResort Entities which derive from Lodging Entity and records are filtered based on the value of the Resort Boolean field =================================================================== Then there is Table per Concrete Type Hierarchy where we create a concrete Entity for each table in the database. In the BreakAway sample there is a entity for the Reservation table and another Entity for the OldReservation table even though both the table contain the same number of fields. The OldReservation Entity can then inherit from the Reservation Entity and configure the OldReservation Entity to remove all Scalar Properties from the Entity (since it inherits the properties from Reservation and filters based on ReservationDate field) =================================================================== Complex Types (Complex Properties) Entities in EF can also contain Complex Properties (in addition to Scalar Properties) and these Complex Properties reference a ComplexType (not a EntityType) DropdownList, ListBox, RadioButtonList, CheckboxList, Bulletedlist are examples of List server controls (not data bound controls) these controls cannot use Complex properties during databinding, they need Scalar Properties. So if a Entity contains Complex properties and you need to bind those to list server controls then use projections to return Scalar properties and bind them to the control (the disadvantage is that projected collections are not tracked by the Object Context and hence cannot persist changes to the projected collections bound to controls) ObjectDataSource and EntityDataSource do account for Complex properties and one can bind entities with Complex Properties to Data Source controls and they will be tracked for changes... with no additional plumbing needed to persist changes to these collections bound to controls So DataBound controls like GridView, FormView need to use EntityDataSource or ObjectDataSource as a datasource for entities that contain Complex properties so that changes to the datasource done using the GridView can be persisted to the DB (enabling the controls for updates)....if you cannot use the EntityDataSource you need to flatten the ComplexType Properties using projections With EF Version 4 ComplexTypes are supported by the Designer and can add/remove/compose Complex Types directly using the Designer =================================================================== Conditional Mapping ... is like Table per Hierarchy Inheritance where Entities inherit from a base class and then used conditions to populate the EntitySet (called conditional Mapping). Conditional Mapping has limitations since you can only use =, is null and IS NOT NULL Conditions to do conditional mapping. If you need more operators for filtering/mapping conditionally then use QueryView(or possibly Defining Query) to create a readonly entity. QueryView are readonly by default... the EntitySet created by the QueryView is enabled for change tracking by the ObjectContext, however the ObjectContext cannot create insert/update/delete TSQL statements for these Entities when SaveChanges is called since it is QueryView. One way to get around this limitation is to map stored procedures for the insert/update/delete operations in the Designer. =================================================================== Difference between QueryView and Defining Query : QueryView is defined in the (MSL) Mapping File/section of the EDM XML, whereas the DefiningQuery is defined in the store schema (SSDL). QueryView is written using Entity SQL and is this database agnostic and can be used against any database/Data Layer. DefiningQuery is written using Database Lanaguage i.e. TSQL or PSQL thus you have more control =================================================================== Performance: Lazy loading is deferred loading done automatically. lazy loading is supported with EF version4 and is on by default. If you need to turn it off then use context.ContextOptions.lazyLoadingEnabled = false To improve Performance consider PreCompiling the ObjectQuery using the CompiledQuery.Compile method

    Read the article

  • Entity Framework: Delete Object and its related entities

    - by Waheed
    Hi, Does anyone know how to delete an object and all of it's related entities. For example i have tables, Products, Category, ProductCategory and productDetails, the productCategory is joining table of both Product and Category. I have red from http://msdn.microsoft.com/en-us/library/bb738580.aspx that Deleting the parent object also deletes all the child objects in the constrained relationship. This result is the same as enabling the CascadeDelete property on the association for the relationship. I am using this code Product productObj = this.ObjectContext.Product.Where(p => p.ProductID.Equals(productID)).First(); if (!productObj.ProductCategory.IsLoaded) productObj.ProductCategory.Load(); if (!productObj.ProductDetails.IsLoaded) productObj.ProductDetails.Load(); //my own methods. base.Delete(productObj); base.SaveAllObjectChanges(); But i am getting error on ObjectContext.SaveChanges(); i.e A relationship is being added or deleted from an AssociationSet 'FK_ProductCategory_Product'. With cardinality constraints, a corresponding 'ProductCategory' must also be added or deleted. Thanks in advance....

    Read the article

  • EF 4, POCO and AddOrUpdate

    - by Eric J.
    I'm trying to create a method on an EF 4 POCO repository called AddOrUpdate. The idea is that the business layer can pass in a POCO object and the persistence framework will add the object if it is new (not yet in the database), else will update the database (once SaveChanges() is called) with the new value. This is similar to some other questions I have asked about EF, but I'm only about 80% there in understanding this so please forgive partial duplication. The part I'm missing is how to update the object graph in my ObjectContext/associated ObjectSet for the passed-in business object once I have determined that the business object indeed already exists in the database (and now has been loaded thanks to TryGetObjectByKey). ApplyCurrentValues sounds sort of like what I want, but it only copies scalar values and doesn't seem intended to update the object graph in the ObjectContext/ObjectSet. Because of my particular use case I don't care about concurrency right now. public void AddOrUpdate(BO biz) { object obj; EntityKey ek = Ctx.CreateEntityKey(mySetName, biz); bool found = Ctx.TryGetObjectByKey(ek, out obj); if (found) { // How do I do what this method name implies? Biz is a parent with children. mySet.TellTheSetToUpdateThisObject(biz); } else { mySet.AddObject(biz); } Ctx.DetectChanges(); }

    Read the article

  • Collection is empty when it arrives on the client

    - by digiduck
    One of my entities has an EntitySet< property with [Composition], [Include] and [Association] attributes. I populate this collection in my domain service but when I check its contents when it is received on the client, the collection is empty. I am using Silverlight 4 RTM as well as RIA Services 1.0 RTM. Any ideas what I am doing wrong? Here is the code on my service side: public class RegionDto { public RegionDto() { Cities = new EntitySet<CityDto>(); } [Key] public int Id { get; set; } public string Name { get; set; } [Include] [Composition] [Association("RegionDto_CityDto", "Id", "RegionId")] public EntitySet<CityDto> Cities { get; set; } } public class CityDto { [Key] public int Id { get; set; } public int RegionId { get; set; } public string Name { get; set; } } [EnableClientAccess()] public class RegionDomainService : LinqToEntitiesDomainService<RegionEntities> { public IEnumerable<RegionDto> GetRegions() { var regions = (ObjectContext.Regions .Select(x => new RegionDto { Id = x.ID, Name = x.Name })).ToList(); foreach (var region in regions) { var cities = (ObjectContext.Cities .Where(x => x.RegionID == region.Id) .Select(x => new CityDto { Id = x.ID, Name = x.Name })).ToList(); foreach (var city in cities) { region.Cities.Add(city); } } // each region's Cities collection is populated at this point // however when the client receives it, the Cities collections are all empty return regions; } }

    Read the article

  • What is the return type for a anonymous linq query select? What is the best way to send this data ba

    - by punkouter
    This is a basic question. I have the basic SL4/RIA project set up and I want to create a new method in the domain service and return some data from it. I am unsure the proper easiest way to do this.. Should I wrap it up in a ToList()? I am unclear how to handle this anonymous type that was create.. what is the easiest way to return this data? public IQueryable<ApplicationLog> GetApplicationLogsGrouped() { var x = from c in ObjectContext.ApplicationLogs let dt = c.LogDate group c by new { y = dt.Value.Year, m = dt.Value.Month, d = dt.Value.Day } into mygroup select new { aaa = mygroup.Key, ProductCount = mygroup.Count() }; return x; // return this.ObjectContext.ApplicationLogs.Where(r => r.ApplicationID < 50); } Cannot implicitly convert type 'System.Linq.IQueryable<AnonymousType#1>' to 'System.Linq.IQueryable<CapRep4.Web.ApplicationLog>'. An explicit conversion exists (are you missing a cast?) 58 20 CapRep4.Web

    Read the article

  • Dataset bind to Gridview within WCF REST retrieval method and Linq to Sql

    - by user643794
    I used a WCF REST template to build a WCF service library to create PUT and GET calls. PUT method works fine sending my blob to a database. On the GET, I want to be able to access the web service directly and display the results from a stored procedure as a dataset and bind this to a gridview. The stored procedure is a simple select statement, returning three of the four columns from the table. I have the following: [WebGet(UriTemplate = "/?name={name}", ResponseFormat = WebMessageFormat.Xml)] public List<Object> GetCollection(string name) { try { db.OpenDbConnection(); // Call to SQL stored procedure return db.GetCustFromName(name); } catch (Exception e) { Log.Error("Stored Proc execution failed. ", e); } finally { db.CloseDbConnection(); } return null; } I also added Linq to SQL class to include my database table and stored procedures access. I also created the Default.aspx file in addition to the other required files. protected void Page_Load(object sender, EventArgs e) { ServiceDataContext objectContext = new ServiceDataContext(); var source = objectContext.GetCustFromName("Tiger"); Menu1.DataSource = source; Menu1.DataBind(); } But this gives me The entity type '' does not belong to any registered model. Where should the data binding be done? What should be the return type for GetCollection()? I am stuck with this. Please provide help on how to do this.

    Read the article

  • Multi threading in WCF RIA Services

    - by synergetic
    I use WCF RIA Services to update customer database. In domain service: public void UpdateCustomer(Customer customer) { this.ObjectContext.Customers.AttachAsModified(customer); syncCustomer(customer); } After update, a database trigger launches and depending on the columns updated it may insert a new record in CustomerChange table. syncCustomer(customer) method is executed to check for a new record in the CustomerChange table and if found it will create a text file which contains customer information and forwards that file to external system for import. Now this synchronization may take a time so I wanted to execute it in different thread. So: private void syncCustomer(Customer customer) { this.ObjectContext.SaveChanges(); new Thread(() => syncCustomerInfo(customer.CustomerID)) { IsBackground = true }.Start(); } private void syncCustomerInfo(int customerID) { //Thread.Sleep(2000); //does real job here ... ... } The problem is in most cases syncCustomerInfo method cannot find any new CustomerChange record even if it was definitely there. If I force thread sleep then it finds a new record. I also looked Entity Framework events but the only event provided by object context is SavingChanges which occur before changes are saved. Please suggest me what else to try.

    Read the article

  • Howw to add new value with generic Repository if there are foreign keys (EF-4)?

    - by Phsika
    i try to write a kind of generic repository to add method. Everything is ok to add but I have table which is related with two tables with FOREIGN KEY.But Not working because of foreign key public class DomainRepository<TModel> : IDomainRepository<TModel> where TModel : class { #region IDomainRepository<T> Members private ObjectContext _context; private IObjectSet<TModel> _objectSet; public DomainRepository() { } public DomainRepository(ObjectContext context) { _context = context; _objectSet = _context.CreateObjectSet<TModel>(); } //do something..... public TModel Add<TModel>(TModel entity) where TModel : IEntityWithKey { EntityKey key; object originalItem; key = _context.CreateEntityKey(entity.GetType().Name, entity); _context.AddObject(key.EntitySetName, entity); _context.SaveChanges(); return entity; } //do something..... } Calling REPOSITORY: //insert-update-delete public partial class AddtoTables { public table3 Add(int TaskId, int RefAircraftsId) { using (DomainRepository<table3> repTask = new DomainRepository<table3>(new TaskEntities())) { return repTask.Add<table3>(new table3() { TaskId = TaskId, TaskRefAircraftsID = RefAircraftsId }); } } } How to add a new value if this table includes foreign key relation

    Read the article

  • Inheritance Mapping Strategies with Entity Framework Code First CTP5: Part 3 – Table per Concrete Type (TPC) and Choosing Strategy Guidelines

    - by mortezam
    This is the third (and last) post in a series that explains different approaches to map an inheritance hierarchy with EF Code First. I've described these strategies in previous posts: Part 1 – Table per Hierarchy (TPH) Part 2 – Table per Type (TPT)In today’s blog post I am going to discuss Table per Concrete Type (TPC) which completes the inheritance mapping strategies supported by EF Code First. At the end of this post I will provide some guidelines to choose an inheritance strategy mainly based on what we've learned in this series. TPC and Entity Framework in the Past Table per Concrete type is somehow the simplest approach suggested, yet using TPC with EF is one of those concepts that has not been covered very well so far and I've seen in some resources that it was even discouraged. The reason for that is just because Entity Data Model Designer in VS2010 doesn't support TPC (even though the EF runtime does). That basically means if you are following EF's Database-First or Model-First approaches then configuring TPC requires manually writing XML in the EDMX file which is not considered to be a fun practice. Well, no more. You'll see that with Code First, creating TPC is perfectly possible with fluent API just like other strategies and you don't need to avoid TPC due to the lack of designer support as you would probably do in other EF approaches. Table per Concrete Type (TPC)In Table per Concrete type (aka Table per Concrete class) we use exactly one table for each (nonabstract) class. All properties of a class, including inherited properties, can be mapped to columns of this table, as shown in the following figure: As you can see, the SQL schema is not aware of the inheritance; effectively, we’ve mapped two unrelated tables to a more expressive class structure. If the base class was concrete, then an additional table would be needed to hold instances of that class. I have to emphasize that there is no relationship between the database tables, except for the fact that they share some similar columns. TPC Implementation in Code First Just like the TPT implementation, we need to specify a separate table for each of the subclasses. We also need to tell Code First that we want all of the inherited properties to be mapped as part of this table. In CTP5, there is a new helper method on EntityMappingConfiguration class called MapInheritedProperties that exactly does this for us. Here is the complete object model as well as the fluent API to create a TPC mapping: public abstract class BillingDetail {     public int BillingDetailId { get; set; }     public string Owner { get; set; }     public string Number { get; set; } }          public class BankAccount : BillingDetail {     public string BankName { get; set; }     public string Swift { get; set; } }          public class CreditCard : BillingDetail {     public int CardType { get; set; }     public string ExpiryMonth { get; set; }     public string ExpiryYear { get; set; } }      public class InheritanceMappingContext : DbContext {     public DbSet<BillingDetail> BillingDetails { get; set; }              protected override void OnModelCreating(ModelBuilder modelBuilder)     {         modelBuilder.Entity<BankAccount>().Map(m =>         {             m.MapInheritedProperties();             m.ToTable("BankAccounts");         });         modelBuilder.Entity<CreditCard>().Map(m =>         {             m.MapInheritedProperties();             m.ToTable("CreditCards");         });                 } } The Importance of EntityMappingConfiguration ClassAs a side note, it worth mentioning that EntityMappingConfiguration class turns out to be a key type for inheritance mapping in Code First. Here is an snapshot of this class: namespace System.Data.Entity.ModelConfiguration.Configuration.Mapping {     public class EntityMappingConfiguration<TEntityType> where TEntityType : class     {         public ValueConditionConfiguration Requires(string discriminator);         public void ToTable(string tableName);         public void MapInheritedProperties();     } } As you have seen so far, we used its Requires method to customize TPH. We also used its ToTable method to create a TPT and now we are using its MapInheritedProperties along with ToTable method to create our TPC mapping. TPC Configuration is Not Done Yet!We are not quite done with our TPC configuration and there is more into this story even though the fluent API we saw perfectly created a TPC mapping for us in the database. To see why, let's start working with our object model. For example, the following code creates two new objects of BankAccount and CreditCard types and tries to add them to the database: using (var context = new InheritanceMappingContext()) {     BankAccount bankAccount = new BankAccount();     CreditCard creditCard = new CreditCard() { CardType = 1 };                      context.BillingDetails.Add(bankAccount);     context.BillingDetails.Add(creditCard);     context.SaveChanges(); } Running this code throws an InvalidOperationException with this message: 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: AcceptChanges cannot continue because the object's key values conflict with another object in the ObjectStateManager. Make sure that the key values are unique before calling AcceptChanges. The reason we got this exception is because DbContext.SaveChanges() internally invokes SaveChanges method of its internal ObjectContext. ObjectContext's SaveChanges method on its turn by default calls AcceptAllChanges after it has performed the database modifications. AcceptAllChanges method merely iterates over all entries in ObjectStateManager and invokes AcceptChanges on each of them. Since the entities are in Added state, AcceptChanges method replaces their temporary EntityKey with a regular EntityKey based on the primary key values (i.e. BillingDetailId) that come back from the database and that's where the problem occurs since both the entities have been assigned the same value for their primary key by the database (i.e. on both BillingDetailId = 1) and the problem is that ObjectStateManager cannot track objects of the same type (i.e. BillingDetail) with the same EntityKey value hence it throws. If you take a closer look at the TPC's SQL schema above, you'll see why the database generated the same values for the primary keys: the BillingDetailId column in both BankAccounts and CreditCards table has been marked as identity. How to Solve The Identity Problem in TPC As you saw, using SQL Server’s int identity columns doesn't work very well together with TPC since there will be duplicate entity keys when inserting in subclasses tables with all having the same identity seed. Therefore, to solve this, either a spread seed (where each table has its own initial seed value) will be needed, or a mechanism other than SQL Server’s int identity should be used. Some other RDBMSes have other mechanisms allowing a sequence (identity) to be shared by multiple tables, and something similar can be achieved with GUID keys in SQL Server. While using GUID keys, or int identity keys with different starting seeds will solve the problem but yet another solution would be to completely switch off identity on the primary key property. As a result, we need to take the responsibility of providing unique keys when inserting records to the database. We will go with this solution since it works regardless of which database engine is used. Switching Off Identity in Code First We can switch off identity simply by placing DatabaseGenerated attribute on the primary key property and pass DatabaseGenerationOption.None to its constructor. DatabaseGenerated attribute is a new data annotation which has been added to System.ComponentModel.DataAnnotations namespace in CTP5: public abstract class BillingDetail {     [DatabaseGenerated(DatabaseGenerationOption.None)]     public int BillingDetailId { get; set; }     public string Owner { get; set; }     public string Number { get; set; } } As always, we can achieve the same result by using fluent API, if you prefer that: modelBuilder.Entity<BillingDetail>()             .Property(p => p.BillingDetailId)             .HasDatabaseGenerationOption(DatabaseGenerationOption.None); Working With The Object Model Our TPC mapping is ready and we can try adding new records to the database. But, like I said, now we need to take care of providing unique keys when creating new objects: using (var context = new InheritanceMappingContext()) {     BankAccount bankAccount = new BankAccount()      {          BillingDetailId = 1                          };     CreditCard creditCard = new CreditCard()      {          BillingDetailId = 2,         CardType = 1     };                      context.BillingDetails.Add(bankAccount);     context.BillingDetails.Add(creditCard);     context.SaveChanges(); } Polymorphic Associations with TPC is Problematic The main problem with this approach is that it doesn’t support Polymorphic Associations very well. After all, in the database, associations are represented as foreign key relationships and in TPC, the subclasses are all mapped to different tables so a polymorphic association to their base class (abstract BillingDetail in our example) cannot be represented as a simple foreign key relationship. For example, consider the the domain model we introduced here where User has a polymorphic association with BillingDetail. This would be problematic in our TPC Schema, because if User has a many-to-one relationship with BillingDetail, the Users table would need a single foreign key column, which would have to refer both concrete subclass tables. This isn’t possible with regular foreign key constraints. Schema Evolution with TPC is Complex A further conceptual problem with this mapping strategy is that several different columns, of different tables, share exactly the same semantics. This makes schema evolution more complex. For example, a change to a base class property results in changes to multiple columns. It also makes it much more difficult to implement database integrity constraints that apply to all subclasses. Generated SQLLet's examine SQL output for polymorphic queries in TPC mapping. For example, consider this polymorphic query for all BillingDetails and the resulting SQL statements that being executed in the database: var query = from b in context.BillingDetails select b; Just like the SQL query generated by TPT mapping, the CASE statements that you see in the beginning of the query is merely to ensure columns that are irrelevant for a particular row have NULL values in the returning flattened table. (e.g. BankName for a row that represents a CreditCard type). TPC's SQL Queries are Union Based As you can see in the above screenshot, the first SELECT uses a FROM-clause subquery (which is selected with a red rectangle) to retrieve all instances of BillingDetails from all concrete class tables. The tables are combined with a UNION operator, and a literal (in this case, 0 and 1) is inserted into the intermediate result; (look at the lines highlighted in yellow.) EF reads this to instantiate the correct class given the data from a particular row. A union requires that the queries that are combined, project over the same columns; hence, EF has to pad and fill up nonexistent columns with NULL. This query will really perform well since here we can let the database optimizer find the best execution plan to combine rows from several tables. There is also no Joins involved so it has a better performance than the SQL queries generated by TPT where a Join is required between the base and subclasses tables. Choosing Strategy GuidelinesBefore we get into this discussion, I want to emphasize that there is no one single "best strategy fits all scenarios" exists. As you saw, each of the approaches have their own advantages and drawbacks. Here are some rules of thumb to identify the best strategy in a particular scenario: If you don’t require polymorphic associations or queries, lean toward TPC—in other words, if you never or rarely query for BillingDetails and you have no class that has an association to BillingDetail base class. I recommend TPC (only) for the top level of your class hierarchy, where polymorphism isn’t usually required, and when modification of the base class in the future is unlikely. If you do require polymorphic associations or queries, and subclasses declare relatively few properties (particularly if the main difference between subclasses is in their behavior), lean toward TPH. Your goal is to minimize the number of nullable columns and to convince yourself (and your DBA) that a denormalized schema won’t create problems in the long run. If you do require polymorphic associations or queries, and subclasses declare many properties (subclasses differ mainly by the data they hold), lean toward TPT. Or, depending on the width and depth of your inheritance hierarchy and the possible cost of joins versus unions, use TPC. By default, choose TPH only for simple problems. For more complex cases (or when you’re overruled by a data modeler insisting on the importance of nullability constraints and normalization), you should consider the TPT strategy. But at that point, ask yourself whether it may not be better to remodel inheritance as delegation in the object model (delegation is a way of making composition as powerful for reuse as inheritance). Complex inheritance is often best avoided for all sorts of reasons unrelated to persistence or ORM. EF acts as a buffer between the domain and relational models, but that doesn’t mean you can ignore persistence concerns when designing your classes. SummaryIn this series, we focused on one of the main structural aspect of the object/relational paradigm mismatch which is inheritance and discussed how EF solve this problem as an ORM solution. We learned about the three well-known inheritance mapping strategies and their implementations in EF Code First. Hopefully it gives you a better insight about the mapping of inheritance hierarchies as well as choosing the best strategy for your particular scenario. Happy New Year and Happy Code-Firsting! References ADO.NET team blog Java Persistence with Hibernate book a { color: #5A99FF; } a:visited { color: #5A99FF; } .title { padding-bottom: 5px; font-family: Segoe UI; font-size: 11pt; font-weight: bold; padding-top: 15px; } .code, .typeName { font-family: consolas; } .typeName { color: #2b91af; } .padTop5 { padding-top: 5px; } .padTop10 { padding-top: 10px; } .exception { background-color: #f0f0f0; font-style: italic; padding-bottom: 5px; padding-left: 5px; padding-top: 5px; padding-right: 5px; }

    Read the article

< Previous Page | 1 2 3 4 5 6 7  | Next Page >