Search Results

Search found 7266 results on 291 pages for 'entity relationship'.

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

  • 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

  • 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 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

  • 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

  • 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

  • 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 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

  • 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

  • How to create relationship between two tables with revisions using Entity Framework

    - by Chris Ridenour
    So I am in the process of redesigning a small database (and potentially a much larger one) but want to show the value of using revisions / history of the business objects. I am switching the data from Access to MSSQL 2008. I am having a lot of internal debate on what version of "revision history" to use in the design itself - and thought I had decided to add a "RevisionId" to all tables. With this design - adding a RevisionId to all tables we would like tracked - what would be the best way to create Navigational Properties and Relationships between two tables such as | Vendor | VendorContact | where a Vendor can have multiple contacts. The Contacts themselves will be under revision. Will it require custom extensions or am I over thinking this? Thanks in advance.

    Read the article

  • Missing something with Entity Framework for .NET 3.5?

    - by AC
    Is it not possible to have EF create the necessary entities when I have two related tables linked with a FK in .NET3.5SP1? I see where the checkbox to support this is disabled but it is available in .NET4. I've got a DB that has only tables with relationships in it. I need to build a Silverlight app (SL4) that allows management of the data within this app. I can't use .NET4 on the server... only .NET3.5SP1 so FK relationship bit in EF4 isn't available to me. Looking to avoid building as much of the plumbing to get back to the DB from the SL4 app as possible...

    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

  • 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 - Insert/Update new entity with child-entities

    - by Christina Mayers
    I have found many questions here on SO and articles all over the internet but none really tackled my problem. My model looks like this (I striped all non essential Properties): Everyday or so "Play" gets updated (via a XML-file containing the information). internal Play ParsePlayInfo(XDocument doc) { Play play = (from p in doc.Descendants("Play") select new Play { Theatre = new Theatre() { //Properties }, //Properties LastUpdate = DateTime.Now }).SingleOrDefault(); var actors = (from a in doc.XPathSelectElement(".//Play//Actors").Nodes() select new Lecturer() { //Properties }); var parts = (from p in doc.XPathSelectElement(".//Play//Parts").Nodes() select new Part() { //Properties }).ToList(); foreach (var item in parts) { play.Parts.Add(item); } var reviews = (from r in doc.XPathSelectElement(".//Play//Reviews").Nodes() select new Review { //Properties }).ToList(); for (int i = 0; i < reviews.Count(); i++) { PlayReviews pR = new PlayReviews() { Review = reviews[i], Play = play, //Properties }; play.PlayReviews.Add(pR); } return play; } If I add this "play" via Add() every Childobject of Play will be inserted - regardless if some exist already. Since I need to update existing entries I have to do something about that. As far as I can tell I have the following options: add/update the child entities in my PlayRepositories Add-Method restructure and rewrite ParsePlayInfo() so that get all the child entities first, add or update them and then create a new Play. The only problem I have here is that I wanted ParsePlayInfo() to be persistence ignorant, I could work around this by creating multiple parse methods (eg ParseActors() ) and assign them to play in my controller (I'm using ASP.net MVC) after everything was parsed and added Currently I am implementing option 1 - but it feels wrong. I'd appreciate it if someone could guide me in the right direction on this one.

    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

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