Search Results

Search found 49963 results on 1999 pages for 'entity system'.

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

  • How a "Collision System" should be implemented?

    - by nathan
    My game is written using a entity system approach using Artemis Framework. Right know my collision detection is called from the Movement System but i'm wondering if it's a proper way to do collision detection using such an approach. Right know i'm thinking of a new system dedicated to collision detection that would proceed all the solid entities to check if they are in collision with another one. I'm wondering if it's a correct way to handle collision detection with an entity system approach? Also, how should i implement this collision system? I though of an IntervalEntitySystem that would check every 200ms (this value is chosen regarding the Artemis documentation) if some entities are colliding. protected void processEntities(ImmutableBag<Entity> ib) { for (int i = 0; i < ib.size(); i++) { Entity e = ib.get(i); //check of collision with other entities here } }

    Read the article

  • Entity binding WPF

    - by morphsd
    I'm doing some auction sale app and I'm new to Entity Framework. I used quickest way to create and bind Wpf control and entity(wizard and drag and drop) so VS2010 generated a lot of code for me. Now I have a problem... WPF control isn't syched to my entity. I read some articles and I understood that I have to use IObservable. Is there an easy way to do that without writing that generated code manually?

    Read the article

  • Execute a SQlite command with Entity Framework

    - by Filimindji
    Hi everybody, I use a SQLite database and Entity Framework (with .net framework 3.5). I'm trying to execute a simple SQL non query command to create a new table in this datase. My Entity Framework already contains the object model for this table : I just want to generate the corresponding table using a command. (By the way, there is maybe a better way to do this. Any ideas someone :) My problem is that I'm not able to execute any command, even the simple commands. Here is my code : EntityConnection entityConnection = new EntityConnection(entitiesConnectionString); Entities db = new Entities(entityConnection); DbCommand command = db.Connection.CreateCommand(); command.CommandText ="CREATE TABLE MyTable (Id int NOT NULL, OtherTable_Id nchar(40) REFERENCES OtherTable (Id) On Delete CASCADE On Update NO ACTION, SomeData nvarchar(1024) NOT NULL, Primary Key(Id) );"; command.ExecuteNonQuery(); I got this error : System.Data.EntitySqlException: The query syntax is not valid., near identifier 'TABLE', line 1, column 8. at System.Data.Common.EntitySql.CqlParser.yyerror(String s) at System.Data.Common.EntitySql.CqlParser.yyparse() at System.Data.Common.EntitySql.CqlParser.Parse(String query) at System.Data.Common.EntitySql.CqlQuery.Parse(String query, ParserOptions parserOptions) at System.Data.Common.EntitySql.CqlQuery.Compile(String query, Perspective perspective, ParserOptions parserOptions, Dictionary`2 parameters, Dictionary`2 variables, Boolean validateTree) at System.Data.EntityClient.EntityCommand.MakeCommandTree() at System.Data.EntityClient.EntityCommand.CreateCommandDefinition() at System.Data.EntityClient.EntityCommand.TryGetEntityCommandDefinitionFromQueryCache(EntityCommandDefinition& entityCommandDefinition) at System.Data.EntityClient.EntityCommand.GetCommandDefinition() at System.Data.EntityClient.EntityCommand.InnerPrepare() at System.Data.EntityClient.EntityCommand.ExecuteReader(CommandBehavior behavior) at System.Data.EntityClient.EntityCommand.ExecuteScalar[T_Result](Func`2 resultSelector) It's seem to be a syntax error, but I can't figure where is the problem and how to resolve it. The entityConnection is ok because I can use any entities generated with EF. I tried with another simple command, but it throw another exception : DbCommand command = db.Connection.CreateCommand(); command.CommandText = "SELECT COUNT(Id) From OtherTable;"; int result = (int)command.ExecuteScalar(); And I got this error, witch is not the same, but may help : System.Data.EntitySqlException: 'Groupe' could not be resolved in the current scope or context. Make sure that all referenced variables are in scope, that required schemas are loaded, and that namespaces are referenced correctly., near simple identifier, line 1, column 23. at System.Data.Common.EntitySql.CqlErrorHelper.ReportIdentifierError(Expr expr, SemanticResolver sr) at System.Data.Common.EntitySql.SemanticAnalyzer.ConvertIdentifier(Expr expr, SemanticResolver sr) at System.Data.Common.EntitySql.SemanticAnalyzer.Convert(Expr astExpr, SemanticResolver sr) at System.Data.Common.EntitySql.SemanticAnalyzer.ProcessAliasedFromClauseItem(AliasExpr aliasedExpr, SemanticResolver sr) at System.Data.Common.EntitySql.SemanticAnalyzer.ProcessFromClauseItem(FromClauseItem fromClauseItem, SemanticResolver sr) at System.Data.Common.EntitySql.SemanticAnalyzer.ProcessFromClause(FromClause fromClause, SemanticResolver sr) at System.Data.Common.EntitySql.SemanticAnalyzer.ConvertQuery(Expr expr, SemanticResolver sr) at System.Data.Common.EntitySql.SemanticAnalyzer.Convert(Expr astExpr, SemanticResolver sr) at System.Data.Common.EntitySql.SemanticAnalyzer.ConvertRootExpression(Expr astExpr, SemanticResolver sr) at System.Data.Common.EntitySql.SemanticAnalyzer.ConvertGeneralExpression(Expr astExpr, SemanticResolver sr) at System.Data.Common.EntitySql.CqlQuery.AnalyzeSemantics(Expr astExpr, Perspective perspective, ParserOptions parserOptions, Dictionary`2 parameters, Dictionary`2 variables) at System.Data.Common.EntitySql.CqlQuery.Compile(String query, Perspective perspective, ParserOptions parserOptions, Dictionary`2 parameters, Dictionary`2 variables, Boolean validateTree) at System.Data.EntityClient.EntityCommand.MakeCommandTree() at System.Data.EntityClient.EntityCommand.CreateCommandDefinition() at System.Data.EntityClient.EntityCommand.TryGetEntityCommandDefinitionFromQueryCache(EntityCommandDefinition& entityCommandDefinition) at System.Data.EntityClient.EntityCommand.GetCommandDefinition() at System.Data.EntityClient.EntityCommand.InnerPrepare() at System.Data.EntityClient.EntityCommand.ExecuteReader(CommandBehavior behavior) at System.Data.EntityClient.EntityCommand.ExecuteScalar[T_Result](Func`2 resultSelector)

    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

  • SQL Server backward compatibility in Entity Framework?

    - by shake
    Is there any backward compatibility in the entity framework between SQL Server 2008 and 2005? It seems the framework forces you to use the same provider for all the .edmx files in a solution. If you use the 2008 provider, data types like DateTime2 and functions like SysDateTime that are emitted by the framework to the underlying SQL query make it useless to use them against a SQL 2005 Server. Any way around this?

    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 Code-First to Provide Replacement for ASP.NET Profile Provider

    - by Ken Cox [MVP]
    A while back, I coordinated a project to add support for the SQL Table Profile Provider in ASP.NET 4 Web Applications.  We urged Microsoft to improve ASP.NET’s built-in Profile support so our workaround wouldn’t be necessary. Instead, Microsoft plans to provide a replacement for ASP.NET Profile in a forthcoming release. In response to my feature suggestion on Connect, Microsoft says we should look for something even better using Entity Framework: “When code-first is officially released the final piece of a full replacement of the ASP.NET Profile will have arrived. Once code-first for EF4 is released, developers will have a really easy and very approachable way to create any arbitrary class, and automatically have the .NET Framework create a table to provide storage for that class. Furthermore developer will also have full LINQ-query capabilities against code-first classes. “ The downside is that there won’t be a way to retrofit this Profile replacement to pre- ASP.NET 4 Web applications. At least there’ll still be the MVP workaround code. It looks like it’s time for me to dig into a CTP of EF Code-First to see what’s available.   Scott Guthrie has been blogging about Code-First Development with Entity Framework 4. It’s not clear when the EF Code-First is coming, but my guess is that it’ll be part of the VS 2010/.NET 4 service pack.

    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 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 - MySQL - Datetime format issue

    - by effkay
    Hello; I have a simple table with few date fields. Whenever I run following query: var docs = ( from d in base.EntityDataContext.document_reviews select d ).ToList(); I get following exception: Unable to convert MySQL date/time value to System.DateTime. MySql.Data.Types.MySqlConversionException: Unable to convert MySQL date/time value to System.DateTime The document reviews table has two date/time fields. One of them is nullable. I have tried placing following in connection string: Allow Zero Datetime=true; But I am still getting exception. Anyone with a solution?

    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

  • 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

  • Localized tables and Entity Framework

    - by Pyttroll
    Hi all, I have a scenario where I need to localized values of objects in my database. Let's say you have an application that can create animals, if the user is english the value of the "Name" property of an animal would be entered as "Cat" in the UI whereas it would be entered as "Chat" in french. The animal culture table would contain 2 records pointing to the same animal in the parent table. When reading values back, if the value of "Name" does not exist in the user culture the default value (value the object was originally created with) would be used. The following diagrams demonstrate how the data is stored in SQL: I'm trying to map this schema to an object model using the Entity Framework, I'm a bit confused as to what the best way to approach the problem. Is EF appropriate for this? Should I used EF4? This EF model will be used by .NET RIA Services. Thanks, Pierre-Yves Troel Ayuda Media Systems http://www.ayudasystems.com

    Read the article

  • Disable Foreign Key Exposure in Entity Framework?

    - by davemackey
    When I originally created a Dynamic Data project I told it to expose the foreign keys, but now I can't make mappings between two entities b/c of the foreign keys. When I click on mapping details while focused on my association I receive the message: Mappings are not allow for an association over exposed foreign keys. So I'd like to disable the exposure of the foreign keys but am unsure how to do this without creating a new Entity Model from scratch. I'm not far along - so that wouldn't be hard, but I imagine there must be a programmatic switch for this?

    Read the article

  • Entity framework support for table valued functions and thus full text

    - by simonsabin
    One of my most popular posts with over 10, 000 hits is how to enable full text when using LINQ to SQL http://sqlblogcasts.com/blogs/simons/archive/2008/12/18/LINQ-to-SQL---Enabling-Fulltext-searching.aspx , core to this is the use of a table valued function. I’m therefore interested to see that Entity Framework will support table valued functions in the next release for more details have a read of the efdesign blog http://blogs.msdn.com/b/efdesign/archive/2011/01/21/table-valued-function-support...(read more)

    Read the article

  • How to implement EntityDataSource Where IN entity sql clause

    - by TonyS
    I want to pass a number of values into a parameter of the EntityDataSource, e.g.: Where="it.ORDER_ID IN {@OrderIdList}" (this is a property on the EntityDataSource) <WhereParameters> <asp:ControlParameter Name="OrderIdList" Type="Int16" ControlID="OrderFilterControl" PropertyName="OrderIdList" /> </WhereParameters> This doesn't work as ORDER_ID is of type int32 and I need to pass in multiple values, e.g. {1,2,3} etc The next thing I tried was setting the Where clause in code-behind and this all works except I can't get data binding on DropDownLists to work. By this I mean no value is returned from the bound dropdownlists in the EntityDataSource Updating Event. My ideal solution would be to use a WhereParameter on the EntityDataSource but any help is appreciated. Thanks, Tony. A complete code example follows using the AdventureWorks db: Public Class EntityDataSourceWhereInClause Inherits System.Web.UI.Page Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load CustomersEntityDataSource.Where = WhereClause ''# reset after each postback as its lost otherwise End Sub Private Sub cmdFilterCustomers_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles cmdFilterCustomers.Click Dim CustomerIdList As New Generic.List(Of Int32) For Each item As ListItem In CustomerIdCheckBoxList.Items If item.Selected Then CustomerIdList.Add(item.Value) End If Next Dim CustomerCsvList As String = String.Join(", ", CustomerIdList.Select(Function(o) o.ToString()).ToArray()) WhereClause = "it.CustomerID IN {" & CustomerCsvList & "}" CustomersEntityDataSource.Where = WhereClause FormView1.PageIndex = 0 End Sub ''# save between postbacks the custom Where IN clause Public Property WhereClause() As String Get Return ViewState("WhereClause") End Get Set(ByVal value As String) ViewState.Add("WhereClause", value) End Set End Property Private Sub CustomersEntityDataSource_Updating(ByVal sender As Object, ByVal e As System.Web.UI.WebControls.EntityDataSourceChangingEventArgs) Handles CustomersEntityDataSource.Updating Dim c = CType(e.Entity, EntityFrameworkTest.Customer) If c.Title.Length = 0 Then Response.Write("Title is empty string, so will save like this!") End If End Sub End Class <%@ Page Language="vb" AutoEventWireup="false" CodeBehind="EntityDataSourceWhereInClause.aspx.vb" Inherits="EntityFrameworkTest.EntityDataSourceWhereInClause" %> <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html xmlns="http://www.w3.org/1999/xhtml"> <head runat="server"> <title></title> </head> <body> <form id="form1" runat="server"> <%''# filter control %> <div> <asp:EntityDataSource ID="CustomerIdListEntityDataSource" runat="server" ConnectionString="name=AdventureWorksLT2008Entities" DefaultContainerName="AdventureWorksLT2008Entities" EnableFlattening="False" EntitySetName="Customers" Select="it.[CustomerID]" OrderBy="it.[CustomerID]"> </asp:EntityDataSource> <asp:CheckBoxList ID="CustomerIdCheckBoxList" runat="server" DataSourceID="CustomerIdListEntityDataSource" DataTextField="CustomerID" DataValueField="CustomerID" RepeatDirection="Horizontal"> </asp:CheckBoxList> <asp:Button ID="cmdFilterCustomers" runat="server" Text="Apply Filter" /> </div> <% ''# you get this error passing in CSV in the where clause ''# The element type 'Edm.Int32' and the CollectionType 'Transient.collection[Edm.String(Nullable=True,DefaultValue=,MaxLength=,Unicode=,FixedLength=)]' are not compatible. The IN expression only supports entity, primitive, and reference types. Near WHERE predicate, line 6, column 15. ''# so have coded it manually in code-behind Where="it.CustomerID IN {@OrderIdList}" %> <asp:EntityDataSource ID="CustomersEntityDataSource" runat="server" ConnectionString="name=AdventureWorksLT2008Entities" DefaultContainerName="AdventureWorksLT2008Entities" EnableFlattening="False" EnableUpdate="True" EntitySetName="Customers" AutoGenerateOrderByClause="false"> </asp:EntityDataSource> <%''# updating works with DropDownLists until the Where clause is set in code %> <asp:FormView ID="FormView1" runat="server" AllowPaging="True" CellPadding="4" DataKeyNames="CustomerID" DataSourceID="CustomersEntityDataSource" ForeColor="#333333"> <EditItemTemplate> CustomerID: <asp:Label ID="CustomerIDLabel1" runat="server" Text='<%# Eval("CustomerID") %>' /> <br /> NameStyle: <asp:CheckBox ID="NameStyleCheckBox" runat="server" Checked='<%# Bind("NameStyle") %>' /> <br /> Title: <%''# the SelectedValue is not Bound to the EF object if the Where clause is updated in code-behind %> <asp:DropDownList ID="ddlTitleBound" runat="server" DataSourceID="TitleEntityDataSource" DataTextField="Title" DataValueField="Title" AutoPostBack="false" AppendDataBoundItems="true" SelectedValue='<%# Bind("Title") %>'> </asp:DropDownList> <asp:EntityDataSource ID="TitleEntityDataSource" runat="server" ConnectionString="name=AdventureWorksLT2008Entities" DefaultContainerName="AdventureWorksLT2008Entities" EnableFlattening="False" EntitySetName="Customers" Select="it.[Title]" GroupBy="it.[Title]" ViewStateMode="Enabled"> </asp:EntityDataSource> <br /> FirstName: <asp:TextBox ID="FirstNameTextBox" runat="server" Text='<%# Bind("FirstName") %>' /> <br /> MiddleName: <asp:TextBox ID="MiddleNameTextBox" runat="server" Text='<%# Bind("MiddleName") %>' /> <br /> LastName: <asp:TextBox ID="LastNameTextBox" runat="server" Text='<%# Bind("LastName") %>' /> <br /> Suffix: <asp:TextBox ID="SuffixTextBox" runat="server" Text='<%# Bind("Suffix") %>' /> <br /> CompanyName: <asp:TextBox ID="CompanyNameTextBox" runat="server" Text='<%# Bind("CompanyName") %>' /> <br /> SalesPerson: <asp:TextBox ID="SalesPersonTextBox" runat="server" Text='<%# Bind("SalesPerson") %>' /> <br /> EmailAddress: <asp:TextBox ID="EmailAddressTextBox" runat="server" Text='<%# Bind("EmailAddress") %>' /> <br /> Phone: <asp:TextBox ID="PhoneTextBox" runat="server" Text='<%# Bind("Phone") %>' /> <br /> PasswordHash: <asp:TextBox ID="PasswordHashTextBox" runat="server" Text='<%# Bind("PasswordHash") %>' /> <br /> PasswordSalt: <asp:TextBox ID="PasswordSaltTextBox" runat="server" Text='<%# Bind("PasswordSalt") %>' /> <br /> rowguid: <asp:TextBox ID="rowguidTextBox" runat="server" Text='<%# Bind("rowguid") %>' /> <br /> ModifiedDate: <asp:TextBox ID="ModifiedDateTextBox" runat="server" Text='<%# Bind("ModifiedDate") %>' /> <br /> <asp:LinkButton ID="UpdateButton" runat="server" CausesValidation="True" CommandName="Update" Text="Update" /> &nbsp;<asp:LinkButton ID="UpdateCancelButton" runat="server" CausesValidation="False" CommandName="Cancel" Text="Cancel" /> </EditItemTemplate> <EditRowStyle BackColor="#999999" /> <FooterStyle BackColor="#5D7B9D" Font-Bold="True" ForeColor="White" /> <HeaderStyle BackColor="#5D7B9D" Font-Bold="True" ForeColor="White" /> <ItemTemplate> CustomerID: <asp:Label ID="CustomerIDLabel" runat="server" Text='<%# Eval("CustomerID") %>' /> <br /> NameStyle: <asp:CheckBox ID="NameStyleCheckBox" runat="server" Checked='<%# Bind("NameStyle") %>' Enabled="false" /> <br /> Title: <asp:Label ID="TitleLabel" runat="server" Text='<%# Bind("Title") %>' /> <br /> FirstName: <asp:Label ID="FirstNameLabel" runat="server" Text='<%# Bind("FirstName") %>' /> <br /> MiddleName: <asp:Label ID="MiddleNameLabel" runat="server" Text='<%# Bind("MiddleName") %>' /> <br /> LastName: <asp:Label ID="LastNameLabel" runat="server" Text='<%# Bind("LastName") %>' /> <br /> Suffix: <asp:Label ID="SuffixLabel" runat="server" Text='<%# Bind("Suffix") %>' /> <br /> CompanyName: <asp:Label ID="CompanyNameLabel" runat="server" Text='<%# Bind("CompanyName") %>' /> <br /> SalesPerson: <asp:Label ID="SalesPersonLabel" runat="server" Text='<%# Bind("SalesPerson") %>' /> <br /> EmailAddress: <asp:Label ID="EmailAddressLabel" runat="server" Text='<%# Bind("EmailAddress") %>' /> <br /> Phone: <asp:Label ID="PhoneLabel" runat="server" Text='<%# Bind("Phone") %>' /> <br /> PasswordHash: <asp:Label ID="PasswordHashLabel" runat="server" Text='<%# Bind("PasswordHash") %>' /> <br /> PasswordSalt: <asp:Label ID="PasswordSaltLabel" runat="server" Text='<%# Bind("PasswordSalt") %>' /> <br /> rowguid: <asp:Label ID="rowguidLabel" runat="server" Text='<%# Bind("rowguid") %>' /> <br /> ModifiedDate: <asp:Label ID="ModifiedDateLabel" runat="server" Text='<%# Bind("ModifiedDate") %>' /> <br /> <asp:LinkButton ID="EditButton" runat="server" CausesValidation="False" CommandName="Edit" Text="Edit" /> </ItemTemplate> <PagerSettings Position="Top" /> <PagerStyle BackColor="#284775" ForeColor="White" HorizontalAlign="Center" /> <RowStyle BackColor="#F7F6F3" ForeColor="#333333" /> </asp:FormView> </form>

    Read the article

  • Error reached after genereated entity framework classes by edmgen tool

    - by loviji
    Hello, First I read this question, but this knowledge did not help to solve my problems. In initial I've created edmx file by Visual Studio. Generated files with names: uqsModel.Designer.cs uqsModel.edmx This files are located on App_Code folder. And my web app work normally. In Web Config generated connectionstring automatically. <add name="uqsEntities" connectionString="metadata=res://*/App_Code.uqsModel.csdl|res://*/App_Code.uqsModel.ssdl|res://*/App_Code.uqsModel.msl;provider=System.Data.SqlClient;provider connection string=&quot;Data Source=aemloviji\sqlexpress;Initial Catalog=uqs;Integrated Security=True;MultipleActiveResultSets=True&quot;" providerName="System.Data.EntityClient" /></connectionStrings> Then I had to generate classes by the instrument edmgen tool(full generation mode). Generated new files with names: uqsModel.cs uqsModel.csdl uqsModel.msl uqsModel.ssdl uqsViews.cs it save new classed to the folder where edmx files located before, and remove existing edmx files. And when page redirrects to any web page server side code fails. And problem: Unable to load the specified metadata resource. Some idea, please.

    Read the article

  • Save entity with entity framework

    - by Michel
    Hi, I'm saving entities/records with the EF, but i'm curious if there is another way of doing it. I receive a class from a MVC controller method, so basicly i have all the info: the class's properties, including the primary key. Without EF i would do a Sql update (update table set a=b, c=d where id = 5), but with EF i got no further than this: Get an object with ID of 5 Update the (existing) object with the new object Submitchanges. What bothers me is that i have to get the object from the database first, where i have all the info to do an update statement. Is there another way of doing this?

    Read the article

  • Entity Framework Update Entity along with child entities (add/update as necessary)

    - by Jorin
    I have a many-to-many relationship between Issues and Scopes in my EF Context. In ASP.NET MVC, I bring up an Edit form that allows the user to edit a particular Issue. At the bottom of the form, is a list of checkboxes that allow them to select which scopes apply to this issue. When editing an issue, it likely will always have some Scopes associated with it already--these boxes will be checked already. However, the user has the opportunity to check more scopes or remove some of the currently checked scopes. My code looked something like this to save just the Issue: using (var edmx = new MayflyEntities()) { Issue issue = new Issue { IssueID = id, TSColumn = formIssue.TSColumn }; edmx.Issues.Attach(issue); UpdateModel(issue); if (ModelState.IsValid) { //if (edmx.SaveChanges() != 1) throw new Exception("Unknown error. Please try again."); edmx.SaveChanges(); TempData["message"] = string.Format("Issue #{0} successfully modified.", id); } } So, when I try to add in the logic to save the associated scopes, I tried several things, but ultimately, this is what made the most sense to me: using (var edmx = new MayflyEntities()) { Issue issue = new Issue { IssueID = id, TSColumn = formIssue.TSColumn }; edmx.Issues.Attach(issue); UpdateModel(issue); foreach (int scopeID in formIssue.ScopeIDs) { var thisScope = new Scope { ID = scopeID }; edmx.Scopes.Attach(thisScope); thisScope.ProjectID = formIssue.ProjectID; if (issue.Scopes.Contains(thisScope)) { issue.Scopes.Attach(thisScope); //the scope already exists } else { issue.Scopes.Add(thisScope); // the scope needs to be added } } if (ModelState.IsValid) { //if (edmx.SaveChanges() != 1) throw new Exception("Unknown error. Please try again."); edmx.SaveChanges(); TempData["message"] = string.Format("Issue #{0} successfully modified.", id); } } But, unfortunately, that just throws the following exception: An object with the same key already exists in the ObjectStateManager. The ObjectStateManager cannot track multiple objects with the same key. What am I doing wrong?

    Read the article

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