Search Results

Search found 16252 results on 651 pages for 'entity framework'.

Page 6/651 | < Previous Page | 2 3 4 5 6 7 8 9 10 11 12 13  | Next Page >

  • Adding existing entity to navigation property of a different entity

    - by Shay Friedman
    I'm using EF4 and I'm running into a problem when I try to do something that looks quite trivial to me. I have two entities, let's call them A and B. These entities have a many-to-many association between them with a navigation property on A that contains a list of related B entities. What I want to do is to add existing B entities to a new A entity. When I try to do that, I get an exception: 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. Has anyone run into such a problem?

    Read the article

  • Deleting entity with child relationships using .Net Entity Framework problem

    - by Am
    My God, EF is so frustrating. I can't seem to be able to get my head around what I need to do so I can delete an object. I seem to be able to remove the object but not the related child objects. Can anyone tell me what is the rule of thumb when you want to delete all related child objects of a given object? I've tried loading all related objects like this: if (!object.childobjects.IsLoaded) object.childobjects.Load(); but once I do the following I get errors related to the relationships: modelcontext.DeleteObject(object); modelcontext.SaveChanges(); Why can't I just load the object using modelcontext.GetObjectByKey and remove it along with its child objects? My other question is can I delete an object using Entity command like so? DELETE e from objectset as e where e.id = 12 I've tried few variations and all of them throw exceptions.

    Read the article

  • RIA Services - Two entity models share an entity name

    - by Alex
    I have two entity models hooked up to two different databases. However, the two databases both have a table named 'brand', for example. As such, there is a naming conflict in my models. Now, I've been able to add a namespace to each model, via Custom Tool Namespace in the model's properties, but the generated code in my Silverlight project will try to use both namespaces, and come up with this, Imports MyProject.ModelA Imports MyProject.ModelB Public ReadOnly Property brands() As EntitySet(Of brand) Get Return MyBase.EntityContainer.GetEntitySet(Of brand) End Get End Property giving me this exception: 'Error 1 'brand' is ambiguous, imported from the namespaces or types 'MyProject.ModelA,MyProject.ModelB'. Has anyone had experience with naming conflicts like this using RIA services? How did you solve it?

    Read the article

  • Entity Framework 4.1 auto generate with DbContext when creating ADO.NET Entity Data Model

    - by smudgedlens
    I would like to work with DbContext instead of ObjectContext. I updated EF so now I have the DbContext, but I want to generate my strongly-typed context based on the DbContext and not the ObjectContext. When I add new ADO.NET Entity Data Model, it is still based on the ObjectContext. Is it not possible to have it base off of DbContext in Visual Studio 2010 with EF 4.1? UPDATE: Okay, I followed the directions in this link and was able to generate the DbContext template objects. However, now it is saying there is ambiguity between the template entities and the entities in my .edmx file. How do I resovle this? Do I blow away the ones in the .edmx file?

    Read the article

  • Role of an entity state in a component based system?

    - by Paul
    Component-based entity systems are all the rage these days; everyone seems to agree they are the way to go, but no one really has a definitive implementation of such a system. I was wondering, what role do entity states (walking-left, standing, jumping, etc) have in a CBS? Do they act like controllers (i.e. they handle events and change the entity's attributes based on those events)? What about cases where a state would, for example, require that the entity enters no-clip mode? Should, that state, when it enters, maybe set the CollisionComponent of the entity to a null pointer or something? (Then, on exit, the state should restore the entity's CollisionComponent to its previous state.) Also, I guess it's the current state's job to change the entity's state to something else, right?

    Read the article

  • Entity Framework - Foreign key constraints not added for inherited entity

    - by Tri Q
    Hello, It appears to me that a strange phenomenon is occurring with inherited entities (TPT) in EF4. I have three entities. 1. Asset 2. Property 3. Activity Property is a derived-type of Asset. Property has many activities (many-to-many) When modeling this in my EDMX, everything seems fine until I try to insert a new Property into the database. If the property does not contain any Activity, it works, but all hell breaks loose when I add some new activities to the new Property. As it turns out after 2 days of crawling the web and fiddling around, I noticed that in the EF store (SSDL) some of the constraints between entities were not picked up during the update process. Property_Activity table which links properties and activities show only one constraint FK_Property_Activity_Activity but FK_Property_Activity_Property was missing. I knew this is an Entity Framework anomoly because when I switched the relationship in the database to: Asset <-- Asset_Activity <-- Activity After an update, all foreign key constraints are picked up and the save is successful, with or without activities in the new property. Is this intended or a bug in EF? How do I get around this problem? Should I abandon inheritance altogether?

    Read the article

  • Entity Framework and differences between Contains between SQL and objects using ToLower

    - by John Ptacek
    I have run into an "issue" I am not quite sure I understand with Entity Framework. I am using Entity Framework 4 and have tried to utilize a TDD approach. As a result, I recently implemented a search feature using a Repository pattern. For my test project, I am implementing my repository interface and have a set of "fake" object data I am using for test purposes. I ran into an issue trying to get the Contains clause to work for case invariant search. My code snippet for both my test and the repository class used against the database is as follows: if (!string.IsNullOrEmpty(Description)) { items = items.Where(r => r.Description.ToLower().Contains(Description.ToLower())); } However, when I ran my test cases the results where not populated if my case did not match the underlying data. I tried looking into what I thought was an issue for a while. To clear my mind, I went for a run and wondered if the same code with EF would work against a SQL back end database, since SQL will explicitly support the like command and it executed as I expected, using the same logic. I understand why EF against the database back end supports the Contains clause. However, I was surprised that my unit tests did not. Any ideas why other than the SQL server support of the like clause when I use objects I populate in a collection instead of against the database server? Thanks! John

    Read the article

  • Seeding many to many tables with Entity Framework

    - by Doozer1979
    I have a meeting entity and a users entity which have a many to many relationship. I'm using Autopoco to create seed data for the Users and meetings How do i seed the UserMeetings linking table that is created by EntityFramework with seed data? The linking table has two fields in it; User_Id, and Meeting_ID. I'm looping through the list of users that autopoco creates and attaching a random number of meetings Here's what i've got so far. foreach (var user in userList) { var rand = new Random(); var amountOfMeetingsToAdd = rand.Next(1, 300); for (var i = 0; i <= amountOfMeetingsToAdd; i++) { var randomMeeting = rand.Next(1, MeetingRecords); //Error occurs on This line user.Meetings.Add(_meetings[randomMeeting]); } } I got an 'Object reference not set to an instance of an object.' even though the meeting record that i'm trying to attach does exist. For info all this is happening prior to me saving the context to the DB.

    Read the article

  • Entity Framework one-to-one relationship mapping flattened in code

    - by Josh Close
    I have a table structure like so. Address: AddressId int not null primary key identity ...more columns AddressContinental: AddressId int not null primary key identity foreign key to pk of Address County State AddressInternational: AddressId int not null primary key identity foreign key to pk of Address ProvinceRegion I don't have control over schema, this is just the way it is. Now, what I want to do is have a single Address object. public class Address { public int AddressId { get; set; } public County County { get; set; } public State State { get; set } public ProvinceRegion { get; set; } } I want to have EF pull it out of the database as a single entity. When saving, I want to save the single entity and have EF know to split it into the three tables. How would I map this in EF 4.1 Code First? I've been searching around and haven't found anything that meets my case yet. UPDATE An address record will have a record in Address and one in either AddressContinental or AddressInternational, but not both.

    Read the article

  • Problem resolving a generic Repository with Entity Framework and Castle Windsor Container

    - by user368776
    Hi, im working in a generic repository implementarion with EF v4, the repository must be resolved by Windsor Container. First the interface public interface IRepository<T> { void Add(T entity); void Delete(T entity); T Find(int key) } Then a concrete class implements the interface public class Repository<T> : IRepository<T> where T: class { private IObjectSet<T> _objectSet; } So i need _objectSet to do stuff like this in the previous class public void Add(T entity) { _objectSet.AddObject(entity); } And now the problem, as you can see im using a EF interface like IObjectSet to do the work, but this type requires a constraint for the T generic type "where T: class". That constrait is causing an exception when Windsor tries to resolve its concrete type. Windsor configuration look like this. <castle> <components> <component id="LVRepository" service="Repository.Infraestructure.IRepository`1, Repository" type="Repository.Infraestructure.Repository`1, Repository" lifestyle="transient"> </component> </components> The container resolve code IRepository<Product> productsRep =_container.Resolve<IRepository<Product>>(); Now the exception im gettin System.ArgumentException: GenericArguments[0], 'T', on 'Repository.Infraestructure.Repository`1[T]' violates the constraint of type 'T'. ---> System.TypeLoadException: GenericArguments[0], 'T', on 'Repository.Infraestructure.Repository`1[T]' violates the constraint of type parameter 'T'. If i remove the constraint in the concrete class and the depedency on IObjectSet (if i dont do it get a compile error) everything works FINE, so i dont think is a container issue, but IObjectSet is a MUST in the implementation. Some help with this, please.

    Read the article

  • Entity Framework naming conventions for many-to-many link tables

    - by TimothyP
    Hi, We are designing a SQL Server database with link tables for many-to-many relations. The question is are there any best practices for naming these kinds of tables for use with the entity framework? Let's say there's a table Customer and Address Then there is a link table between them, what do we call it? CustomerAddress ? Or something else? Thnx

    Read the article

  • How to create entities in one Entity group ?

    - by Gopi
    I am building an app based on google app engine (Java) using JDO for persistence. Can someone give me an example or a point me to some code which shows persisting of multiple entities (of same type) using javax.jdo.PersistenceManager.makePersistentAll() within a transaction. Basically I need to understand how to put multiple entites in one Entity Group so that they can be saved using makePersistentAll() inside transaction.

    Read the article

  • Entity Framework ObjectContext Life-cycle

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

    Read the article

  • Entity Association Mapping with Code First Part 1 : Mapping Complex Types

    - by mortezam
    Last week the CTP5 build of the new Entity Framework Code First has been released by data team at Microsoft. Entity Framework Code-First provides a pretty powerful code-centric way to work with the databases. When it comes to associations, it brings ultimate flexibility. I’m a big fan of the EF Code First approach and am planning to explain association mapping with code first in a series of blog posts and this one is dedicated to Complex Types. If you are new to Code First approach, you can find a great walkthrough here. In order to build a solid foundation for our discussion, we will start by learning about some of the core concepts around the relationship mapping.   What is Mapping?Mapping is the act of determining how objects and their relationships are persisted in permanent data storage, in our case, relational databases. What is Relationship mapping?A mapping that describes how to persist a relationship (association, aggregation, or composition) between two or more objects. Types of RelationshipsThere are two categories of object relationships that we need to be concerned with when mapping associations. The first category is based on multiplicity and it includes three types: One-to-one relationships: This is a relationship where the maximums of each of its multiplicities is one. One-to-many relationships: Also known as a many-to-one relationship, this occurs when the maximum of one multiplicity is one and the other is greater than one. Many-to-many relationships: This is a relationship where the maximum of both multiplicities is greater than one. The second category is based on directionality and it contains two types: Uni-directional relationships: when an object knows about the object(s) it is related to but the other object(s) do not know of the original object. To put this in EF terminology, when a navigation property exists only on one of the association ends and not on the both. Bi-directional relationships: When the objects on both end of the relationship know of each other (i.e. a navigation property defined on both ends). How Object Relationships Are Implemented in POCO domain models?When the multiplicity is one (e.g. 0..1 or 1) the relationship is implemented by defining a navigation property that reference the other object (e.g. an Address property on User class). When the multiplicity is many (e.g. 0..*, 1..*) the relationship is implemented via an ICollection of the type of other object. How Relational Database Relationships Are Implemented? Relationships in relational databases are maintained through the use of Foreign Keys. A foreign key is a data attribute(s) that appears in one table and must be the primary key or other candidate key in another table. With a one-to-one relationship the foreign key needs to be implemented by one of the tables. To implement a one-to-many relationship we implement a foreign key from the “one table” to the “many table”. We could also choose to implement a one-to-many relationship via an associative table (aka Join table), effectively making it a many-to-many relationship. Introducing the ModelNow, let's review the model that we are going to use in order to implement Complex Type with Code First. It's a simple object model which consist of two classes: User and Address. Each user could have one billing address. The Address information of a User is modeled as a separate class as you can see in the UML model below: In object-modeling terms, this association is a kind of aggregation—a part-of relationship. Aggregation is a strong form of association; it has some additional semantics with regard to the lifecycle of objects. In this case, we have an even stronger form, composition, where the lifecycle of the part is fully dependent upon the lifecycle of the whole. Fine-grained domain models The motivation behind this design was to achieve Fine-grained domain models. In crude terms, fine-grained means “more classes than tables”. For example, a user may have both a billing address and a home address. In the database, you may have a single User table with the columns BillingStreet, BillingCity, and BillingPostalCode along with HomeStreet, HomeCity, and HomePostalCode. There are good reasons to use this somewhat denormalized relational model (performance, for one). In our object model, we can use the same approach, representing the two addresses as six string-valued properties of the User class. But it’s much better to model this using an Address class, where User has the BillingAddress and HomeAddress properties. This object model achieves improved cohesion and greater code reuse and is more understandable. Complex Types: Splitting a Table Across Multiple Types Back to our model, there is no difference between this composition and other weaker styles of association when it comes to the actual C# implementation. But in the context of ORM, there is a big difference: A composed class is often a candidate Complex Type. But C# has no concept of composition—a class or property can’t be marked as a composition. The only difference is the object identifier: a complex type has no individual identity (i.e. no AddressId defined on Address class) which make sense because when it comes to the database everything is going to be saved into one single table. How to implement a Complex Types with Code First Code First has a concept of Complex Type Discovery that works based on a set of Conventions. The convention is that if Code First discovers a class where a primary key cannot be inferred, and no primary key is registered through Data Annotations or the fluent API, then the type will be automatically registered as a complex type. Complex type detection also requires that the type does not have properties that reference entity types (i.e. all the properties must be scalar types) and is not referenced from a collection property on another type. Here is the implementation: public class User{    public int UserId { get; set; }    public string FirstName { get; set; }    public string LastName { get; set; }    public string Username { get; set; }    public Address Address { get; set; }} public class Address {     public string Street { get; set; }     public string City { get; set; }            public string PostalCode { get; set; }        }public class EntityMappingContext : DbContext {     public DbSet<User> Users { get; set; }        } With code first, this is all of the code we need to write to create a complex type, we do not need to configure any additional database schema mapping information through Data Annotations or the fluent API. Database SchemaThe mapping result for this object model is as follows: Limitations of this mappingThere are two important limitations to classes mapped as Complex Types: Shared references is not possible: The Address Complex Type doesn’t have its own database identity (primary key) and so can’t be referred to by any object other than the containing instance of User (e.g. a Shipping class that also needs to reference the same User Address). No elegant way to represent a null reference There is no elegant way to represent a null reference to an Address. When reading from database, EF Code First always initialize Address object even if values in all mapped columns of the complex type are null. This means that if you store a complex type object with all null property values, EF Code First returns a initialized complex type when the owning entity object is retrieved from the database. SummaryIn this post we learned about fine-grained domain models which complex type is just one example of it. Fine-grained is fully supported by EF Code First and is known as the most important requirement for a rich domain model. Complex type is usually the simplest way to represent one-to-one relationships and because the lifecycle is almost always dependent in such a case, it’s either an aggregation or a composition in UML. In the next posts we will revisit the same domain model and will learn about other ways to map a one-to-one association that does not have the limitations of the complex types. References ADO.NET team blog Mapping Objects to Relational Databases Java Persistence with Hibernate

    Read the article

  • Texture switching with a entity system

    - by GameDev-er
    I'm using thinking of using an entity system in my game. So far I've been using Artemis with success. However, I have a question about texture switching. I read that switching textures too often is bad. So I load all the textures when the game loads like so: import org.newdawn.slick.opengl.TextureLoader; ... public HashMap<String, Texture> Textures; ... Then for each texture I do this: Texture tex = TextureLoader.getTexture("PNG", this.getClass().getResourceAsStream(texturePath)); Textures.put(textureName, tex); Then when drawing entities I do this: drawEntity() { glBindTexture(GL_TEXTURE_2D, Textures.get(entityTexture).getTextureID()); ... } Say I have 50 entities, using 10 different 3D models, each with their own texture. When the drawEntity system runs, it doesn't group by which entities use which texture. So I could be switching textures before drawing each entity! Is there a more efficient way to switch textures between entities? Or is glBindTexture() a good option?

    Read the article

  • Entity Framework and distributed Systems

    - by Dirk Beckmann
    I need some help or maybe only a hint for the right direction. I've got a system that is sperated into two applications. An existing VB.NET desktop client using Entity Framework 5 with code first approach and a asp.net Web Api client in C# that will be refactored right yet. It should be possible to deliver OData. The system and the datamodel is still involving and so migrations will happen in undefined intervalls. So I'm now struggling how to manage my database access on the web api system. So my favourd approch would be us Entity Framework on both systems but I'm running into trouble while creating new migrations. Two solutions I've thought about: Shared Data Access dll The first idea was to separate the data access layer to a seperate project an reference from each of the systems. The context would be the same as long as the dll is up to date in each system. This way both soulutions would be able to make a migration. The main problem ist that it is much more complicate to update a web api system than it is with the client Click Once Update Solution and not every migration is important for the web api. This would couse more update trouble and out of sync libraries Database First on Web Api The second idea was just to use the database first approch an on web api side. But it seems that all annotations will be lost by each model update. Other solutions with stored procedures have been discarded because of missing OData support and maintainability. Does anyone run into same conflicts or has any advices how such a problem can be solved!

    Read the article

  • Entity framework separating entities for product and customer specific implementation

    - by Codecat
    I am designing an application with intention into making it a product line. I would like to extend the functionality across all layers and first struggle is with domain models. For example, core functionality would have entity named Invoice with few standard fields and then customer requirements will add some new fields to it, but I don't want to add to core Invoice class. For every customer I could use customer specific DbContext and injected correct context with dependency injection. Also every customer will get they own deployment public class Product.Domain.Invoice { public int InvoiceId { get; set; } // Other fields } How to approach this problem? Solution 1 does not work since Entity Framework does not allow same simple name classes. public class CustomerA.Domain.Invoice : Product.Domain.Invoice { public User ReviewedBy { get; set; } public DateTime? ReviewedOn { get; set; } } Solution 2 Create separate table and link it to core domain table. Reusing services and controllers could be harder. public class CustomerA.Domain.CustomerAInvoice { public Product.Domain.Invoice Invoice { get; set; } public User ReviewedBy { get; set; } public DateTime? ReviewedOn { get; set; } }

    Read the article

  • Entity Framework RC1 DbContext query issue

    - by Steve
    I'm trying to implement the repository pattern using entity framework code first rc 1. The problem I am running into is with creating the DbContext. I have an ioc container resolving the IRepository and it has a contextprovider which just news up a new DbContext with a connection string in a windsor.config file. With linq2sql this part was no problem but EF seems to be choking. I'll describe the problem below with an example. I've pulled out the code to simplify things a bit so that is why you don't see any repository pattern stuff here. just sorta what is happening without all the extra code and classes. using (var context = new PlssContext()) { var x = context.Set<User>(); var y = x.Where(u => u.UserName == LogOnModel.UserName).FirstOrDefault(); } using (var context2 = new DbContext(@"Data Source=.\SQLEXPRESS;Initial Catalog=PLSS.Models.PlssContext;Integrated Security=True;MultipleActiveResultSets=True")) { var x = context2.Set<User>(); var y = x.Where(u => u.UserName == LogOnModel.UserName).FirstOrDefault(); } PlssContext is where I am creating my DbContext class. The repository pattern doesn't know anything about PlssContext. The best I thought I could do was create a DbContext with the connection string to the sqlexpress database and query the data that way. The connection string in the var context2 was grabbed from the context after newing up the PlssContext object. So they are pointing at the same sqlexpress database. The first query works. The second query fails miserably with this error: The model backing the 'DbContext' context has changed since the database was created. Either manually delete/update the database, or call Database.SetInitializer with an IDatabaseInitializer instance. For example, the DropCreateDatabaseIfModelChanges strategy will automatically delete and recreate the database, and optionally seed it with new data. on this line var y = x.Where(u => u.UserName == LogOnModel.UserName).FirstOrDefault(); Here is my DbContext namespace PLSS.Models { public class PlssContext : DbContext { public DbSet<User> Users { get; set; } public DbSet<Corner> Corners { get; set; } public DbSet<Lookup_County> Lookup_County { get; set; } public DbSet<Lookup_Accuracy> Lookup_Accuracy { get; set; } public DbSet<Lookup_MonumentStatus> Lookup_MonumentStatus { get; set; } public DbSet<Lookup_CoordinateSystem> Lookup_CoordinateSystem { get; set; } public class Initializer : DropCreateDatabaseAlways<PlssContext> { protected override void Seed(PlssContext context) { I've tried all of the Initializer strategies with the same errors. I don't think the database is changing. If I remove the modelBuilder.Conventions.Remove<IncludeMetadataConvention>(); Then the error returns is The entity type User is not part of the model for the current context. Which sort of makes sense. But how do you bring this all together?

    Read the article

  • Choosing a CSS grid/framework

    - by jonallard
    There are many grids and framework to choose from. A Google search for CSS frameworks will return a dozen articles that themselves list a number of frameworks to choose from. When it comes to choosing one, it's easy to be lost without having an intimate knowledge of all of them. What are the main factors that go into choosing a CSS framework, and how will those choices map to certain frameworks? More generally, how does one choose a CSS framework? Note 1: I'm using "grid" and "framework" almost interchangeably here, but there is probably one I should use over the other. Corrections on this are welcome. Note 2: I am well aware that some choices will depend on taste and accordingly, this question can turn into a "best of" contest/subjective topic. I'm trying to keep it as answerable as possible, as I'm pretty sure many have this problem/question of choosing a framework and an answer to that would benefit the community. As such, improvements to this question are welcome rather than just closing it.

    Read the article

  • Unique Keys not recognized by Entity Framework

    - by David Pfeffer
    I have two tables, Reports and Visualizations. Reports has a field, VisualizationID, which points to Visualization's field of the same name via a foreign key. It also has a unique key declared on the field. VisualizationID is not nullable. This means the relationship has to be 0..1 to 1, because every Reports record must have a unique, not null Visualizations record associated with it. The Entity Framework doesn't see it this way. I'm getting the following error: Error 113: Multiplicity is not valid in Role 'Report' in relationship 'FK_Reports_Visualizations'. Because the Dependent Role properties are not the key properties, the upper bound of the multiplicity of the Dependent Role must be *. What's the problem here? How can I make the EF recognize the proper relationship multiplicity?

    Read the article

  • 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

< Previous Page | 2 3 4 5 6 7 8 9 10 11 12 13  | Next Page >