Search Results

Search found 39 results on 2 pages for 'entityobject'.

Page 1/2 | 1 2  | Next Page >

  • Entity Framework 4.0 and DDD patterns

    - by Voice
    Hi everybody I use EntityFramework as ORM and I have simple POCO Domain Model with two base classes that represent Value Object and Entity Object Patterns (Evans). These two patterns is all about equality of two objects, so I overrode Equals and GetHashCode methods. Here are these two classes: public abstract class EntityObject<T>{ protected T _ID = default(T); public T ID { get { return _ID; } protected set { _ID = value; } } public sealed override bool Equals(object obj) { EntityObject<T> compareTo = obj as EntityObject<T>; return (compareTo != null) && ((HasSameNonDefaultIdAs(compareTo) || (IsTransient && compareTo.IsTransient)) && HasSameBusinessSignatureAs(compareTo)); } public virtual void MakeTransient() { _ID = default(T); } public bool IsTransient { get { return _ID == null || _ID.Equals(default(T)); } } public override int GetHashCode() { if (default(T).Equals(_ID)) return 0; return _ID.GetHashCode(); } private bool HasSameBusinessSignatureAs(EntityObject<T> compareTo) { return ToString().Equals(compareTo.ToString()); } private bool HasSameNonDefaultIdAs(EntityObject<T> compareTo) { return (_ID != null && !_ID.Equals(default(T))) && (compareTo._ID != null && !compareTo._ID.Equals(default(T))) && _ID.Equals(compareTo._ID); } public override string ToString() { StringBuilder str = new StringBuilder(); str.Append(" Class: ").Append(GetType().FullName); if (!IsTransient) str.Append(" ID: " + _ID); return str.ToString(); } } public abstract class ValueObject<T, U> : IEquatable<T> where T : ValueObject<T, U> { private static List<PropertyInfo> Properties { get; set; } private static Func<ValueObject<T, U>, PropertyInfo, object[], object> _GetPropValue; static ValueObject() { Properties = new List<PropertyInfo>(); var propParam = Expression.Parameter(typeof(PropertyInfo), "propParam"); var target = Expression.Parameter(typeof(ValueObject<T, U>), "target"); var indexPar = Expression.Parameter(typeof(object[]), "indexPar"); var call = Expression.Call(propParam, typeof(PropertyInfo).GetMethod("GetValue", new[] { typeof(object), typeof(object[]) }), new[] { target, indexPar }); var lambda = Expression.Lambda<Func<ValueObject<T, U>, PropertyInfo, object[], object>>(call, target, propParam, indexPar); _GetPropValue = lambda.Compile(); } public U ID { get; protected set; } public override Boolean Equals(Object obj) { if (ReferenceEquals(null, obj)) return false; if (obj.GetType() != GetType()) return false; return Equals(obj as T); } public Boolean Equals(T other) { if (ReferenceEquals(null, other)) return false; if (ReferenceEquals(this, other)) return true; foreach (var property in Properties) { var oneValue = _GetPropValue(this, property, null); var otherValue = _GetPropValue(other, property, null); if (null == oneValue && null == otherValue) return false; if (false == oneValue.Equals(otherValue)) return false; } return true; } public override Int32 GetHashCode() { var hashCode = 36; foreach (var property in Properties) { var propertyValue = _GetPropValue(this, property, null); if (null == propertyValue) continue; hashCode = hashCode ^ propertyValue.GetHashCode(); } return hashCode; } public override String ToString() { var stringBuilder = new StringBuilder(); foreach (var property in Properties) { var propertyValue = _GetPropValue(this, property, null); if (null == propertyValue) continue; stringBuilder.Append(propertyValue.ToString()); } return stringBuilder.ToString(); } protected static void RegisterProperty(Expression<Func<T, Object>> expression) { MemberExpression memberExpression; if (ExpressionType.Convert == expression.Body.NodeType) { var body = (UnaryExpression)expression.Body; memberExpression = body.Operand as MemberExpression; } else memberExpression = expression.Body as MemberExpression; if (null == memberExpression) throw new InvalidOperationException("InvalidMemberExpression"); Properties.Add(memberExpression.Member as PropertyInfo); } } Everything was OK until I tried to delete some related objects (aggregate root object with two dependent objects which was marked for cascade deletion): I've got an exception "The relationship could not be changed because one or more of the foreign-key properties is non-nullable". I googled this and found http://blog.abodit.com/2010/05/the-relationship-could-not-be-changed-because-one-or-more-of-the-foreign-key-properties-is-non-nullable/ I changed GetHashCode to base.GetHashCode() and error disappeared. But now it breaks all my code: I can't override GetHashCode for my POCO objects = I can't override Equals = I can't implement Value Object and Entity Object patters for my POCO objects. So, I appreciate any solutions, workarounds here etc.

    Read the article

  • Unexpected generics behaviour

    - by pronicles
    I found strange generics behaviour. In two words - thing I realy want is to use ComplexObject1 in most general way, and the thing I realy missed is why defined generic type(... extends BuisnessObject) is lost. The discuss thread is also awailable in my blog http://pronicles.blogspot.com/2010/03/unexpected-generics-behaviour.html. public class Test { public interface EntityObject {} public interface SomeInterface {} public class BasicEntity implements EntityObject {} public interface BuisnessObject<E extends EntityObject> { E getEntity(); } public interface ComplexObject1<V extends SomeInterface> extends BusinessObject<BasicEntity> {} public interface ComplexObject2 extends BuisnessObject<BasicEntity> {} public void test(){ ComplexObject1 complexObject1 = null; ComplexObject2 complexObject2 = null; EntityObject entityObject1 = complexObject1.getEntity(); //BasicEntity entityObject1 = complexObject1.getEntity(); wtf incompatible types!!!! BasicEntity basicEntity = complexObject2.getEntity(); } }

    Read the article

  • Service locator for generics

    - by vittore
    Hi everyone, I have say a dozen types T which inherit from EntityObject and IDataObject. I have generic the following interface IDataManager<T> where T : EntityObject, IDataObject ... I have also base class for data managers BaseDataManager<T> : IDataManager<T> where T : EntityObject, IDataObject .... And i have particular classes public class Result : EntityObject, IDataObject .... public class ResultDataManager : BaseDataManager<Result> ... I want to implement service locator, which will return instance of IDataManager<T> for T But I stucked how to implement it in a neat way without a lot of castings. Any ideas?

    Read the article

  • Problem with ModelAndView and ModelMap in AnnotationController, Springframework

    - by saltfactory
    I have a question that is a point difference between ModelAndView and ModelMap. I want to maintain modelAndView when requestMethod is "GET" and requestMethod is "POST". My modelAndView saved others. So I made modelAndView return type to "GET", "POST" methods. But, Request lost commandObject, form:errors..., if request return showForm on "POST" because request validation failed. example) private ModelAndView modelAndView; public ControllerTest{ this.modelAndView = new ModelAndView(); } @RequestMapping(method = RequestMethod.GET) public ModelAndView showForm(ModelMap model) { EntityObject entityObject = new EntityObject(); CommandObject commandObject = new CommandObject(); commandObject.setEntityObject(entityObject); model.addAttribute("commandObject", commandObject); this.modelAndView.addObject("id", "GET"); this.modelAndView.setViewName("registerForm"); return this.modelAndView; } @RequestMapping(method = RequestMethod.POST) public ModelAndView submit(@ModelAttribute("commandObject") CommandObject commandObject, BindingResult result, SessionStatus status) { this.commandValidator.validate(commandObject, result); if (result.hasErrors()) { this.modelAndView.addObject("id", "POST"); this.modelAndView.setViewName("registerForm"); return this.modelAndView; } else { this.modelAndView.addObject("id", "after POST"); this.modelAndView.setViewName("success"); } status.setComplete(); return this.modelAndView; }

    Read the article

  • Brainstorming: Weird JPA problem, possibly classpath or jar versioning problem???

    - by Vinnie
    I'm seeing a weird error message and am looking for some ideas as to what the problem could be. I'm sort of new to using the JPA. I have an application where I'm using Spring's Entity Manager Factory (LocalContainerEntityManagerFactoryBean), EclipseLink as my ORM provider, connected to a MySQL DB and built with Maven. I'm not sure if any of this matters..... When I deploy this application to Glassfish, the application works as expected. The problem is, I've created a set of stand alone unit tests to run outside of Glassfish that aren't working correctly. I get the following error (I've edited the class names a little) com.xyz.abc.services.persistence.entity.MyEntity cannot be cast to com.xyz.abc.services.persistence.entity.MyEntity The object cannot be cast to a class of the same type? How can that be? Here's a snippet of the code that is in error Query q = entityManager.createNamedQuery("MyEntity.findAll"); List entityObjects = q.getResultList(); for (Object entityObject: entityObjects) { com.xyz.abc.services.persistence.entity.MyEntity entity = (com.xyz.abc.services.persistence.entity.MyEntity) entityObject; Previously, I had this code that produced the same error: CriteriaQuery cq = entityManager.getCriteriaBuilder().createQuery(); cq.select(cq.from(com.xyz.abc.services.persistence.entity.MyEntity.class)); List entityObjects = entityManager.createQuery(cq).getResultList(); for (Object entityObject: entityObjects) { com.xyz.abc.services.persistence.entity.MyEntity entity = (com.xyz.abc.services.persistence.entity.MyEntity) entityObject; This code is question is the same that I have deployed to the server. Here's the innermost exception if it helps Caused by: java.lang.ClassCastException: com.xyz.abc.services.persistence.entity.MyEntity cannot be cast to com.xyz.abc.services.persistence.entity.MyEntity at com.xyz.abc.services.persistence.entity.factory.MyEntityFactory.createBeans(MyEntityFactory.java:47) at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method) at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:39) at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:25) at java.lang.reflect.Method.invoke(Method.java:597) at org.springframework.beans.factory.support.SimpleInstantiationStrategy.instantiate(SimpleInstantiationStrategy.java:115) ... 37 more I'm guessing that there's some jar I'm using in Glassfish that is different than the ones I'm using in test. I've looked at all the jars I have listed as "provided" and am pretty sure they are all the same ones from Glassfish. Let me know if you've seen this weird issue before, or any ideas for correcting it.

    Read the article

  • Typecasting EnityObject

    - by AJ
    Hello, I'm new to C# and am stuck on the following. I have a Silverlight web service that uses LINQ to query a ADO.NET entity object. e.g.: [OperationContract] public List<Customer> GetData() { using (TestEntities ctx = new TestEntities()) { var data = from rec in ctx.Customer select rec; return data.ToList(); } } This works fine, but what I want to do is to make this more abstract. The first step would be to return a List<EntityObject> but this gives a compiler error, e.g.: [OperationContract] public List<EntityObject> GetData() { using (TestEntities ctx = new TestEntities()) { var data = from rec in ctx.Customer select rec; return data.ToList(); } } The error is: Error 1 Cannot implicitly convert type 'System.Collections.Generic.List<SilverlightTest.Web.Customer>' to 'System.Collections.Generic.IEnumerable<System.Data.Objects.DataClasses.EntityObject>'. An explicit conversion exists (are you missing a cast?) What am i doing wrong? Thanks, AJ

    Read the article

  • Generic list typecasting problem

    - by AJ
    Hello, I'm new to C# and am stuck on the following. I have a Silverlight web service that uses LINQ to query a ADO.NET entity object. e.g.: [OperationContract] public List<Customer> GetData() { using (TestEntities ctx = new TestEntities()) { var data = from rec in ctx.Customer select rec; return data.ToList(); } } This works fine, but what I want to do is to make this more abstract. The first step would be to return a List<EntityObject> but this gives a compiler error, e.g.: [OperationContract] public List<EntityObject> GetData() { using (TestEntities ctx = new TestEntities()) { var data = from rec in ctx.Customer select rec; return data.ToList(); } } The error is: Error 1 Cannot implicitly convert type 'System.Collections.Generic.List<SilverlightTest.Web.Customer>' to 'System.Collections.Generic.IEnumerable<System.Data.Objects.DataClasses.EntityObject>'. An explicit conversion exists (are you missing a cast?) What am i doing wrong? Thanks, AJ

    Read the article

  • How to bind data in silverlight? In case I don't know which columns would be retrieved from database

    - by kwon
    I am trying to bind data from database to datagrid in silverlight. When I get typed data from DB, it is no problem since I use List<'EntityObject' collection object for example. However, sometimes I need data which I won't be able to know how many and what columns will be generated in design time. In this case, I cannot use typed collection like List<'EntityObject'. In addition, it is not able to use DataSet in silverlight. So, in this case and situation, how to solve this kind of problem? Thanks in advance Kwon

    Read the article

  • Entity Framework with ASP.NET MVC. Updating entity problem

    - by Kitaly
    Hi people. I'm trying to update an entity and its related entities as well. For instance, I have a class Car with a property Category and I want to change its Category. So, I have the following methods in the Controller: public ActionResult Edit(int id) { var categories = context.Categories.ToList(); ViewData["categories"] = new SelectList(categories, "Id", "Name"); var car = context.Cars.Where(c => c.Id == id).First(); return PartialView("Form", car); } [AcceptVerbs(HttpVerbs.Post)] public ActionResult Edit(Car car) { var category = context.Categories.Where(c => c.Id == car.Category.Id).First(); car.Category = category; context.UpdateCar(car); context.SaveChanges(); return RedirectToAction("Index"); } The UpdateCar method, in ObjectContext class, follows: public void UpdateCar(Car car) { var attachedCar = Cars.Where(c => c.Id == car.Id).First(); ApplyItemUpdates(attachedCar, car); } private void ApplyItemUpdates(EntityObject originalItem, EntityObject updatedItem) { try { ApplyPropertyChanges(originalItem.EntityKey.EntitySetName, updatedItem); ApplyReferencePropertyChanges(updatedItem, originalItem); } catch (InvalidOperationException ex) { Console.WriteLine(ex.ToString()); } } public void ApplyReferencePropertyChanges(IEntityWithRelationships newEntity, IEntityWithRelationships oldEntity) { foreach (var relatedEnd in oldEntity.RelationshipManager.GetAllRelatedEnds()) { var oldRef = relatedEnd as EntityReference; if (oldRef != null) { var newRef = newEntity.RelationshipManager.GetRelatedEnd(oldRef.RelationshipName, oldRef.TargetRoleName) as EntityReference; oldRef.EntityKey = newRef.EntityKey; } } } The problem is that when I set the Category property after the POST in my controller, the entity state changes to Added instead of remaining as Detached. How can I update one-to-one relationship with Entity Framework and ASP.NET MVC without setting all the properties, one by one like this post?

    Read the article

  • Entity Framework Custom Query Function

    - by Josh
    I have an Entity Framework 4.0 Entity Object called Revision w/ Nullable DateEffectiveFrom and DateEffectiveTo dates. I was wondering if there was a short-hand way of querying an object's RevisionHistory based on a particular QueryDate date instead of having to use the following query structure: var results = EntityObject.Revisions.Where(x => (x.DateEffectiveFrom == null && x.DateEffectiveTo == null) || (x.DateEffectiveFrom == null && x.DateEffectiveTo >= QueryDate) || (x.DateEffectiveFrom <= QueryDate && x.DateEffectiveTo == null) || (x.DateEffectiveFrom <= QueryDate && x.DateEffectiveTo >= QueryDate)); I've tried creating the following boolean function in the Revision class: partial class Revision { public bool IsEffectiveOn(DateTime date) { return (x.DateEffectiveFrom == null && x.DateEffectiveTo == null) || (x.DateEffectiveFrom == null && x.DateEffectiveTo >= date) || (x.DateEffectiveFrom <= date && x.DateEffectiveTo == null) || (x.DateEffectiveFrom <= date && x.DateEffectiveTo >= date)); } ... } And then updating the query to: var results = EntityObject.Revisions.Where(x => x.IsEffectiveOn(QueryDate)); but this obviously doesn't translate to SQL. Any ideas would be much appreciated.

    Read the article

  • Entity Framework 4.0: Why Would One Use the Code Generated EntityObjects Over POCO Objects?

    - by senfo
    Aside from faster development time (Visual Studio 2010 beta 2 has no T4 templates for building POCO entity objects that I'm aware of), are there any advantages to using the traditional EntityObject entities that Entity Framework creates, by default? If Microsoft delivers a T4 template for building POCO objects, I'm trying to figure out why anybody would want to use the traditional method.

    Read the article

  • The type '' was not mapped

    - by Mike
    I've been trying to fix this error for awhile now. I get this error any time my application tries to create an instance of my data context. Below is the code: using System; using System.Collections.Generic; using System.Linq; using System.Web; using RandomRentals.Models; using System.Data.Entity; namespace RandomRentals.Models { public class RentalContext : DbContext { public DbSet<Rental> Rentals { get; set; } public DbSet<Category> Categories { get; set; } public DbSet<Item> Items { get; set; } public DbSet<Billing> Billings { get; set; } public DbSet<User> Users { get; set; } public DbSet<Video> Videos { get; set; } public DbSet<Picture> Pictures { get; set; } public DbSet<ServiceType> ServiceTypes { get; set; } public DbSet<Rating> Ratings { get; set; } public DbSet<Business> Businesses { get; set; } public DbSet<BusinessHour> BusinessHours { get; set; } } } Here is the stack Trace: [InvalidOperationException: The type 'RandomRentals.Rental' was not mapped. Check that the type has not been explicitly excluded by using the Ignore method or NotMappedAttribute data annotation. Verify that the type was defined as a class, is not primitive, nested or generic, and does not inherit from EntityObject.] System.Data.Entity.Internal.DbSetDiscoveryService.GetSets() +706 System.Data.Entity.Internal.DbSetDiscoveryService.InitializeSets() +31 System.Data.Entity.DbContext.DiscoverAndInitializeSets() +56 System.Data.Entity.DbContext.InitializeLazyInternalContext(IInternalConnection internalConnection, DbCompiledModel model) +79 System.Data.Entity.DbContext..ctor() +99 RandomRentals.Models.RentalContext..ctor() +44 RandomRentals.Models.UserModel..ctor() in C:\Users\nikka\Desktop\RandomRentals\RandomRentals\Models\UserModel.cs:11 [TargetInvocationException: Exception has been thrown by the target of an invocation.] System.RuntimeTypeHandle.CreateInstance(RuntimeType type, Boolean publicOnly, Boolean noCheck, Boolean& canBeCached, RuntimeMethodHandleInternal& ctor, Boolean& bNeedSecurityCheck) +0 System.RuntimeType.CreateInstanceSlow(Boolean publicOnly, Boolean skipCheckThis, Boolean fillCache) +98 System.RuntimeType.CreateInstanceDefaultCtor(Boolean publicOnly, Boolean skipVisibilityChecks, Boolean skipCheckThis, Boolean fillCache) +241 System.Activator.CreateInstance(Type type, Boolean nonPublic) +69 System.Web.Mvc.DefaultModelBinder.CreateModel(ControllerContext controllerContext, ModelBindingContext bindingContext, Type modelType) +199 System.Web.Mvc.DefaultModelBinder.BindComplexModel(ControllerContext controllerContext, ModelBindingContext bindingContext) +572 System.Web.Mvc.DefaultModelBinder.BindModel(ControllerContext controllerContext, ModelBindingContext bindingContext) +449 System.Web.Mvc.ControllerActionInvoker.GetParameterValue(ControllerContext controllerContext, ParameterDescriptor parameterDescriptor) +317 System.Web.Mvc.ControllerActionInvoker.GetParameterValues(ControllerContext controllerContext, ActionDescriptor actionDescriptor) +117 System.Web.Mvc.ControllerActionInvoker.InvokeAction(ControllerContext controllerContext, String actionName) +343 System.Web.Mvc.Controller.ExecuteCore() +116 System.Web.Mvc.ControllerBase.Execute(RequestContext requestContext) +97 System.Web.Mvc.ControllerBase.System.Web.Mvc.IController.Execute(RequestContext requestContext) +10 System.Web.Mvc.<>c__DisplayClassb.<BeginProcessRequest>b__5() +37 System.Web.Mvc.Async.<>c__DisplayClass1.<MakeVoidDelegate>b__0() +21 System.Web.Mvc.Async.<>c__DisplayClass8`1.<BeginSynchronous>b__7(IAsyncResult _) +12 System.Web.Mvc.Async.WrappedAsyncResult`1.End() +62 System.Web.Mvc.<>c__DisplayClasse.<EndProcessRequest>b__d() +50 System.Web.Mvc.SecurityUtil.<GetCallInAppTrustThunk>b__0(Action f) +7 System.Web.Mvc.SecurityUtil.ProcessInApplicationTrust(Action action) +22 System.Web.Mvc.MvcHandler.EndProcessRequest(IAsyncResult asyncResult) +60 System.Web.Mvc.MvcHandler.System.Web.IHttpAsyncHandler.EndProcessRequest(IAsyncResult result) +9 System.Web.CallHandlerExecutionStep.System.Web.HttpApplication.IExecutionStep.Execute() +8970061 System.Web.HttpApplication.ExecuteStep(IExecutionStep step, Boolean& completedSynchronously) +184 Here is the full error text: The type 'RandomRentals.Rental' was not mapped. Check that the type has not been explicitly excluded by using the Ignore method or NotMappedAttribute data annotation. Verify that the type was defined as a class, is not primitive, nested or generic, and does not inherit from EntityObject. Any help would be greatly appreciated

    Read the article

  • StoreGeneratedPattern T4 EntityFramework concern

    - by LoganWolfer
    Hi everyone, Here's the situation : I use SQL Server 2008 R2, SQL Replication, Visual Studio 2010, EntityFramework 4, C# 4. The course-of-action from our DBA is to use a rowguid column for SQL Replication to work with our setup. These columns need to have a StoreGeneratedPattern property set to Computed on every one of these columns. The problem : Every time the T4 template regenerate our EDMX (ADO.NET Entity Data Model) file (for example, when we update it from our database), I need to go manually in the EDMX XML file to add this property to every one of them. It has to go from this : <Property Name="rowguid" Type="uniqueidentifier" Nullable="false" /> To this : <Property Name="rowguid" Type="uniqueidentifier" Nullable="false" StoreGeneratedPattern="Computed"/> The solution : I'm trying to find a way to customize an ADO.NET EntityObject Generator T4 file to generate a StoreGeneratedPattern="Computed" to every rowguid that I have. I'm fairly new to T4, I only did customization to AddView and AddController T4 templates for ASP.NET MVC 2, like List.tt for example. I've looked through the EF T4 file, and I can't seem to find through this monster where I could do that (and how). My best guess is somewhere in this part of the file, line 544 to 618 of the original ADO.NET EntityObject Generator T4 file : //////// //////// Write PrimitiveType Properties. //////// private void WritePrimitiveTypeProperty(EdmProperty primitiveProperty, CodeGenerationTools code) { MetadataTools ef = new MetadataTools(this); #> /// <summary> /// <#=SummaryComment(primitiveProperty)#> /// </summary><#=LongDescriptionCommentElement(primitiveProperty, 1)#> [EdmScalarPropertyAttribute(EntityKeyProperty=<#=code.CreateLiteral(ef.IsKey(primitiveProperty))#>, IsNullable=<#=code.CreateLiteral(ef.IsNullable(primitiveProperty))#>)] [DataMemberAttribute()] <#=code.SpaceAfter(NewModifier(primitiveProperty))#><#=Accessibility.ForProperty(primitiveProperty)#> <#=code.Escape(primitiveProperty.TypeUsage)#> <#=code.Escape(primitiveProperty)#> { <#=code.SpaceAfter(Accessibility.ForGetter(primitiveProperty))#>get { <#+ if (ef.ClrType(primitiveProperty.TypeUsage) == typeof(byte[])) { #> return StructuralObject.GetValidValue(<#=code.FieldName(primitiveProperty)#>); <#+ } else { #> return <#=code.FieldName(primitiveProperty)#>; <#+ } #> } <#=code.SpaceAfter(Accessibility.ForSetter((primitiveProperty)))#>set { <#+ if (ef.IsKey(primitiveProperty)) { if (ef.ClrType(primitiveProperty.TypeUsage) == typeof(byte[])) { #> if (!StructuralObject.BinaryEquals(<#=code.FieldName(primitiveProperty)#>, value)) <#+ } else { #> if (<#=code.FieldName(primitiveProperty)#> != value) <#+ } #> { <#+ PushIndent(CodeRegion.GetIndent(1)); } #> <#=ChangingMethodName(primitiveProperty)#>(value); ReportPropertyChanging("<#=primitiveProperty.Name#>"); <#=code.FieldName(primitiveProperty)#> = StructuralObject.SetValidValue(value<#=OptionalNullableParameterForSetValidValue(primitiveProperty, code)#>); ReportPropertyChanged("<#=primitiveProperty.Name#>"); <#=ChangedMethodName(primitiveProperty)#>(); <#+ if (ef.IsKey(primitiveProperty)) { PopIndent(); #> } <#+ } #> } } private <#=code.Escape(primitiveProperty.TypeUsage)#> <#=code.FieldName(primitiveProperty)#><#=code.StringBefore(" = ", code.CreateLiteral(primitiveProperty.DefaultValue))#>; partial void <#=ChangingMethodName(primitiveProperty)#>(<#=code.Escape(primitiveProperty.TypeUsage)#> value); partial void <#=ChangedMethodName(primitiveProperty)#>(); <#+ } Any help would be appreciated. Thanks in advance. EDIT : Didn't find answer to this problem yet, if anyone have ideas to automate this, would really be appreciated.

    Read the article

  • DomainService method not compiling; claims "Return types must be an entity ..."

    - by Duncan Bayne
    I have a WCF RIA Domain Service that contains a method I'd like to invoke when the user clicks a button: [Invoke] public MyEntity PerformAnalysis(int someId) { return new MyEntity(); } However, when I try to compile I'm given the following error: Operation named 'PerformAnalysis' does not conform to the required signature. Return types must be an entity, collection of entities, or one of the predefined serializable types. The thing is, as far as I can tell, MyEntity is an entity: [Serializable] public class MyEntity: EntityObject, IMyEntity { [Key] [DataMember] [Editable(false)] public int DummyKey { get; set; } [DataMember] [Editable(false)] public IEnumerable<SomeOtherEntity> Children { get; set; } } I figure I'm missing something simple here. Could someone please tell me how I can create an invokable method that returns a single MyEntity object?

    Read the article

  • How to implement paging for datagrid using LINQ to Entities in wpf?

    - by Levelbit
    I'm new in wpf. My main problem is to understand how DataGrid works with its datacontext. It would help me a lot because I don't know how to make a universal paging usercontrol for all my datagrids in the projects for different database tables. DataGrid converts received DataContext from object to some kind of list. How it is implemented. I tried to do some casting from object to IQueryable to generalize thinig because base class of every entity in the entity model is EntityObject class. But it doesen't work in runtime although I don't receive complains at design time.

    Read the article

  • WPF DataGrid duplicates new row when new item is attached to the source collection.

    - by Shimmy
    <Page> <Page.Resources> <data:Quote x:Key="Quote"/> </Page.Resources> <tk:DataGrid DataContext="{Binding Quote}" ItemsSource="{Binding Rooms}"> <tk:DataGrid/> </Page> Code: Private Sub InitializingNewItem _ (sender As DataGrid, _ ByVal e As InitializingNewItemEventArgs) _ Handles dgRooms.InitializingNewItem Dim room = DirectCast(e.NewItem, Room) 'Room is subclass of EntityObject Dim state = room.EntityState 'Detached Dim quote = Resources("Quote") state = quote.EntityState 'Unchanged 'either one of these lines causes the new row to go duplicated: quote.Rooms.Add(room) room.Quote = quote 'I tried: sender.Items.Refresh 'I also tried to remove the detached entity from the DataGrid and create a 'new item but it they throw exceptions saying the the Items is untouchable. End If

    Read the article

  • Asp.Net Program Architecture

    - by Pino
    I've just taken on a new Asp.Net MVC application and after opening it up I find the following, [Project].Web [Project].Models [Project].BLL [Project].DAL Now, something thats become clear is that there is the data has to do a hell of a lot before it makes it to the View (DatabaseDALRepoBLLConvertToModelControllerView). The DAL is Subsonic, the repositorys in the DAL return the subsonic entities to the BLL which process them does crazy things and converts them into a Model (From the .Models) sometimes with classes that look like this public DataModel GetDataModel(EntityObject Src) { var ReturnData = new DataModel(): ReturnData.ID = Src.ID; ReturnDate.Name = Src.Name; //etc etc } Now, the question is, "Is this complete overkill"? Ok the project is of a decent size and can only get bigger but is it worth carrying on with all this? I dont want to use AutoMapper as it just seems like it makes the complication worse. Can anyone shed any light on this?

    Read the article

  • WPF Validation & IDataErrorInfo

    - by Jefim
    A note - the classes I have are EntityObject classes! I have the following class: public class Foo { public Bar Bar { get; set; } } public class Bar : IDataErrorInfo { public string Name { get; set; } #region IDataErrorInfo Members string IDataErrorInfo.Error { get { return null; } } string IDataErrorInfo.this[string columnName] { get { if (columnName == "Name") { return "Hello error!"; } Console.WriteLine("Validate: " + columnName); return null; } } #endregion } XAML goes as follows: <StackPanel Orientation="Horizontal" DataContext="{Binding Foo.Bar}"> <TextBox Text="{Binding Path=Name, ValidatesOnDataErrors=true}"/> </StackPanel> I put a breakpoint and a Console.Writeline on the validation there - I get no breaks. The validation is not executed. Can anybody just press me against the place where my error lies?

    Read the article

  • how VAR is determined against many options?

    - by Royi Namir
    i have this code : IEnumerable<string> q = customers /*EF entity*/ .Select (c => c.Name.ToUpper()) .OrderBy (n => n) To select entity, ObjectContext actually create ObjectQuery, which implement IQueryable. The object return from ObjectQuery, is not normal object, but EntityObject but what if i write : ( notice the var) var q = customers /*EF entity*/ .Select (c => c.Name.ToUpper()) .OrderBy (n => n) it can be determined both to ienumerable or iqueryable : because ObjectQuery Also implements IEnumerable... i dont know if there's any specific info which tell the compiler "use A and not B. A is more specific..." ( there must be...i just cant find it) any help ? how will it know to use A || B ?

    Read the article

  • WFP Validation & IDataErrorInfo

    - by Jefim
    A note - the classes I have are EntityObject classes! I have the following class: public class Foo { public Bar Bar { get; set; } } public class Bar : IDataErrorInfo { public string Name { get; set; } #region IDataErrorInfo Members string IDataErrorInfo.Error { get { return null; } } string IDataErrorInfo.this[string columnName] { get { if (columnName == "Name") { return "Hello error!"; } Console.WriteLine("Validate: " + columnName); return null; } } #endregion } XAML goes as follows: <StackPanel Orientation="Horizontal" DataContext="{Binding Foo.Bar}"> <TextBox Text="{Binding Path=Name, ValidatesOnDataErrors=true}"/> </StackPanel> I put a breakpoint and a Console.Writeline on the validation there - I get no breaks. The validation is not executed. Can anybody just press me against the place where my error lies?

    Read the article

  • [EF + Oracle] Entities

    - by JTorrecilla
    Prologue Following with the Serie I started yesterday about Entity Framework with Oracle, Today I am going to start talking about Entities. What is an Entity? A Entity is an object of the EF model corresponding to a record in a DB table. For example, let’s see, in Image 1 we can see one Entity from our model, and in the second one we can see the mapping done with the DB. (Image 1) (Image 2) More in depth a Entity is a Class inherited from the abstract class “EntityObject”, contained by the “System.Data.Objects.DataClasses” namespace. At the same time, this class inherits from the following Class and interfaces: StructuralObject: It is an Abstract class that inherits from INotifyPropertyChanging and INotifyPropertyChanged interfaces, and it exposes the events that manage the Changes of the class, and the functions related to check the data types of the Properties from our Entity.  IEntityWithKey: Interface which exposes the Key of the entity. IEntityWithChangeTracker: Interface which lets indicate the state of the entity (Detached, Modified, Added…) IEntityWithRelationships: Interface which indicates the relations about the entity. Which is the Content of a Entity? A Entity is composed by: Properties, Navigation Properties and Methods. What is a Property? A Entity Property is an object that represents a column from the mapped table from DB. It has a data type equivalent in .Net Framework to the DB Type. When we create the EF model, VS, internally, create the code for each Entity selected in the Tables step, such all methods that we will see in next steps. For each property, VS creates a structure similar to: · Private variable with the mapped Data type. · Function with a name like On{Property_Name}Changing({dataType} value): It manages the event which happens when we try to change the value. · Function with a name like On{Property_Name}Change: It manages the event raised when the property has changed successfully. · Property with Get and Set methods: The Set Method manages the private variable and do the following steps: Raise Changing event. Report the Entity is Changing. Set the prívate variable. For it, Use the SetValidValue function of the StructuralObject. There is a function for each datatype, and the functions takes 2 params: the value, and if the prop allow nulls. Invoke that the entity has been successfully changed. Invoke the Changed event of the Prop. ReportPropertyChanging and ReportPropertyChanged events, let, respectively, indicate that there is pending changes in the Entity, and the changes have success correctly. While the ReportPropertyChanged is raised, the Track State of the Entity will be changed. What is a Navigation Property? Navigation Properties are a kind of property of the type: EntityCollection<TEntity>, where TEntity is an Entity type from the model related with the current one, it is said, is a set of record from a related table in the DB. The EntityCollection class inherits from: · RelatedEnd: There is an abstract class that give the functions needed to obtein the related objects. · ICollection<TEntity> · IEnumerable<TEntity> · IEnumerable · IListSource For the previous interfaces, I wish recommend the following post from Jose Miguel Torres. Navigation properties allow us, to get and query easily objects related with the Entity. Methods? There is only one method in the Entity object. “Create{Entity}”, that allow us to create an object of the Entity by sending the parameters needed to create it. Finally After this chapter, we know what is an Entity, how is related to the DB and the relation to other Entities. In following chapters, we will se CRUD operations(Create, Read, Update, Delete).

    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

1 2  | Next Page >