Search Results

Search found 9916 results on 397 pages for 'entity component'.

Page 29/397 | < Previous Page | 25 26 27 28 29 30 31 32 33 34 35 36  | Next Page >

  • Entity Framework 4 Code First and the new() Operator

    - by Eric J.
    I have a rather deep hierarchy of objects that I'm trying to persist with Entity Framework 4, POCO, PI (Persistence Ignorance) and Code First. Suddenly things started working pretty well when it dawned on me to not use the new() operator. As originally written, the objects frequently use new() to create child objects. Instead I'm using my take on the Repository Pattern to create all child objects as needed. For example, given: class Adam { List<Child> children; void AddChildGivenInput(string input) { children.Add(new Child(...)); } } class Child { List<GrandChild> grandchildren; void AddGrandChildGivenInput(string input) { grandchildren.Add(new GrandChild(...)); } } class GrandChild { } ("GivenInput" implies some processing not shown here) I define an AdamRepository like: class AdamRepository { Adam Add() { return objectContext.Create<Adam>(); } Child AddChildGivenInput(Adam adam, string input) { return adam.children.Add(new Child(...)); } GrandChild AddGrandchildGivenInput(Child child, string input) { return child.grandchildren.Add(new GrandChild(...)); } } Now, this works well enough. However, I'm no longer "ignorant" of my persistence mechanism as I have abandoned the new() operator. Additionally, I'm at risk of an anemic domain model since so much logic ends up in the repository rather than in the domain objects. After much adieu, a question: Or rather several questions... Is this pattern required to work with EF 4 Code First? Is there a way to retain use of new() and still work with EF 4 / POCO / Code First? Is there another pattern that would leave logic in the domain object and still work with EF 4 / POCO / Code First? Will this restriction be lifted in later versions of Code First support? Sometimes trying to go the POCO / Persistence Ignorance route feels like swimming upstream, other times it feels like swimming up Niagra Falls.

    Read the article

  • Why doesn't TransactionScope work with Entity Framework?

    - by NotDan
    See the code below. If I initialize more than one entity context, then I get the following exception on the 2nd set of code only. If I comment out the second set it works. {"The underlying provider failed on Open."} Inner: {"Communication with the underlying transaction manager has failed."} Inner: {"Error HRESULT E_FAIL has been returned from a call to a COM component."} Note that this is a sample app and I know it doesn't make sense to create 2 contexts in a row. However, the production code does have reason to create multiple contexts in the same TransactionScope, and this cannot be changed. Edit Here is a previous question of me trying to set up MS-DTC. It seems to be enabled on both the server and the client. I'm not sure if it is set up correctly. Also note that one of the reasons I am trying to do this, is that existing code within the TransactionScope uses ADO.NET and Linq 2 Sql... I would like those to use the same transaction also. (That probably sounds crazy, but I need to make it work if possible). http://stackoverflow.com/questions/794364/how-do-i-use-transactionscope-in-c Solution Windows Firewall was blocking the connections to MS-DTC. using(TransactionScope ts = new System.Transactions.TransactionScope()) { using (DatabaseEntityModel o = new DatabaseEntityModel()) { var v = (from s in o.Advertiser select s).First(); v.AcceptableLength = 1; o.SaveChanges(); } //-> By commenting out this section, it works using (DatabaseEntityModel o = new DatabaseEntityModel()) { //Exception on this next line var v = (from s1 in o.Advertiser select s1).First(); v.AcceptableLength = 1; o.SaveChanges(); } //-> ts.Complete(); }

    Read the article

  • Autonumber with Entity Framework

    - by dcompiled
    I want to loop through a collection of objects and add them all to a table. The destination table has an auto-increment field. If I add a single object there is no problem. If I add two objects both with the primary key of zero, the entity framework fails. I can manually specify primary keys but the whole point of trying the EF was to make life easier not more complicated. Here is the code and the exception received follows. foreach (Contact contact in contacts) { Instructor instructor = InstructorFromContact(contact); context.AddToInstructors(instructor); } try { context.SaveChanges(); } catch (Exception ex) { Console.WriteLine(ex.ToString()); } System.InvalidOperationException: The changes to the database were committed successfully, but an error occurred while updating the object context. The ObjectContext might be in an inconsistent state. Inner exception message: AcceptChanges cannot continue because the object's key values conflict with another object in the ObjectStateManager. Make sure that the key values are unique before calling AcceptChanges. at System.Data.Objects.ObjectContext.SaveChanges(SaveOptions options) at System.Data.Objects.ObjectContext.SaveChanges() at DataMigration.Program.CopyInstructors() in C:\Projects\DataMigration\Program.cs:line 52

    Read the article

  • Problem with cascade delete using Entity Framework and System.Data.SQLite

    - by jamone
    I have a SQLite DB that is set up so when I delete a Person the delete is cascaded. This works fine when I manually delete a Person (all records that reference the PersonID are deleted). But when I use Entity Framework to delete the Person I get an error: System.InvalidOperationException: The operation failed: The relationship could not be changed because one or more of the foreign-key properties is non-nullable. When a change is made to a relationship, the related foreign-key property is set to a null value. If the foreign-key does not support null values, a new relationship must be defined, the foreign-key property must be assigned another non-null value, or the unrelated object must be deleted. I don't understand why this is occurring. My trigger is set to clean up all related objects before deleting the object it was told to delete. When I go into the model editor and check the properties of the relationship it shows no action for the OnDelete property. Why isn't this set correctly by pulling it from the DB? If I change this value to Cascade everything works properly, but I would rather not rely on this manual change because what if I refresh my model from the DB and it looses that. Here's the relivent SQL for my tables. CREATE TABLE [SomeTable] ( [SomeTableID] INTEGER NOT NULL PRIMARY KEY AUTOINCREMENT, [PersonID] INTEGER NOT NULL REFERENCES [Person](PersonID) ON DELETE CASCADE ) CREATE TABLE [Person] ( [PersonID] INTEGER NOT NULL PRIMARY KEY AUTOINCREMENT )

    Read the article

  • Problem deleting record using Entity Framework and System.Data.SQLite

    - by jamone
    I have a SQLite DB that is set up so when I delete a Person the delete is cascaded. This works fine when I manually delete a Person (all records that reference the PersonID are deleted). But when I use Entity Framework to delete the Person I get an error: System.InvalidOperationException: The operation failed: The relationship could not be changed because one or more of the foreign-key properties is non-nullable. When a change is made to a relationship, the related foreign-key property is set to a null value. If the foreign-key does not support null values, a new relationship must be defined, the foreign-key property must be assigned another non-null value, or the unrelated object must be deleted. I don't understand why this is occurring. My trigger is set to clean up all related objects before deleting the object it was told to delete. When I go into the model editor and check the properties of the relationship it shows no action for the OnDelete property. Why isn't this set correctly by pulling it from the DB? Here's the relivent SQL for my tables. CREATE TABLE [SomeTable] ( [SomeTableID] INTEGER NOT NULL PRIMARY KEY AUTOINCREMENT, [PersonID] INTEGER NOT NULL REFERENCES [Person](PersonID) ON DELETE CASCADE ) CREATE TABLE [Person] ( [PersonID] INTEGER NOT NULL PRIMARY KEY AUTOINCREMENT )

    Read the article

  • Entity Framework, Foreign Keys and EntityKeys

    - by Greg
    I've got a problem with the Entity Framework and the ForeignKeys. I've got a table "BC_Message_Assets" which has 3 FK's (MessageId, AssetId and StatusId). I create my "MessageAsset" like this MessageAsset messageAsset = new MessageAsset(); messageAsset.MessageStatusReference.EntityKey = new EntityKey("MyEntities.MessageStatusSet", "Id", 1); messageAsset.AssetReference.EntityKey = new EntityKey("MyEntities.AssetSet", "Id", 1); messageAsset.MessageReference.EntityKey = new EntityKey("MyEntities.MessageSet", "Id", messageId); context.AddToMessageAssetSet(messageAsset); context.SaveChanges(); But I got the following exception : The INSERT statement conflicted with the FOREIGN KEY constraint \"FK_BC_Message_Assets_BC_Assets\". The conflict occurred in database \"Test\", table \"dbo.BC_Assets\", column 'Id'.\r\nThe statement has been terminated. When I look at the query, I notice that the parameter value for AssetId is "0" despite that I provided "1" to the EntityKey. Here's the generated query : exec sp_executesql N'insert [dbo].[BC_Message_Assets]([MessageId], [AssetId], [CompletionTime], [StatusId]) values (@0, @1, null, @2) ',N'@0 int,@1 int,@2 int',@0=47,@1=0,@2=1 I can't explain what happens. I hardcoded "1" in the EntityKey and I received "0" in the query ?

    Read the article

  • Entity Framework query not returning correctly enumerated results.

    - by SkippyFire
    I have this really strange problem where my entity framework query isn't enumerating correctly. The SQL Server table I'm using has a table with a Sku field, and the column is "distinct". It isn't a key, but it doesn't contain any duplicate values. Using actual SQL with where, distinct and group by cluases I have confirmed this. However, when I do this: // Not good foreach(var product in dc.Products) or // Not good foreach(var product in dc.Products.ToList()) or // Not good foreach(var product in dc.Products.OrderBy(p => p.Sku)) the first two objects that are returned ARE THE SAME!!! The third item was technically the second item in the table, but then the fourth item was the first row from the table again!!! The only solution I have found is to use the Distinct extension method, which shouldn't really do anything in this situation: // Good foreach(var product in dc.Products.ToList().Distinct()) Another weird thing about this is that the count of the resulting queries is the same!!! So whether or not the resulting enumerable has the correct results or duplicates, I always get the number of rows in the actual table! (No I don't have a limit clause anywhere). What could possibly cause this!?!?!?

    Read the article

  • entity framework POCO template in a n-tiers design question

    - by bryan
    HI all I was trying to follow the POCO Template walkthrough . And now I am having problems using it in n-tiers design. By following the article, I put my edmx model, and the template generated context.tt in my DAL project, and moved the generated model.tt entity classes to my Business Logic layer (BLL) project. By doing this, I could use those entities inside my BLL without referencing the DAL, I guess that is the idea of PI; without knowing anything about the data source. Now, I want to extend the entities (inside the model.tt) to perform some CUD action in the BLL project,so I added a new partial class same name as the one generated from template, public partial class Company { public static IEnumerable AllCompanies() { using(var context = new Entities()){ var q = from p in context.Companies select p; return q.ToList(); } } } however visual studio won't let me do that, and I think it was because the context.tt is in the DAL project, and the BLL project could not add a reference to the DAL project as DAL has already reference to the BLL. So I tried to added this class to the DAL and it compiled, but intelisense won't show up the BLL.Company.AllCompanies() in my web service method from my webservice project which has reference to my BLL project. What should I do now? I want to add CUD methods to the template generated entities in my BLL project, and call them in my web services from another project. I have been looking for this answer a few days already, and I really need some guides from here please. Bryan

    Read the article

  • Entity Framework lazy loading doesn't work from other thread

    - by Thomas Levesque
    Hi, I just found out that lazy loading in Entity Framework only works from the thread that created the ObjectContext. To illustrate the problem, I did a simple test, with a simple model containing just 2 entities : Person and Address. Here's the code : private static void TestSingleThread() { using (var context = new TestDBContext()) { foreach (var p in context.Person) { Console.WriteLine("{0} lives in {1}.", p.Name, p.Address.City); } } } private static void TestMultiThread() { using (var context = new TestDBContext()) { foreach (var p in context.Person) { Person p2 = p; // to avoid capturing the loop variable ThreadPool.QueueUserWorkItem( arg => { Console.WriteLine("{0} lives in {1}.", p2.Name, p2.Address.City); }); } } } The TestSingleThread method works fine, the Address property is lazily loaded. But in TestMultiThread, I get a NullReferenceException on p2.Address.City, because p2.Address is null. It that a bug ? Is this the way it's supposed to work ? If so, is there any documentation mentioning it ? I couldn't find anything on the subject on MSDN or Google... And more importantly, is there a workaround ? (other than explicitly calling LoadProperty from the worker thread...) Any help would be very appreciated PS: I'm using VS2010, so it's EF 4.0. I don't know if it was the same in the previous version of EF...

    Read the article

  • C# Entity FrameWork MySQL Slow Queries Count()

    - by Matthew M.
    Hello, I'm having a serious issue with MySQL and Entity Framework 4.0. I have dropped a Table onto the EF Designer surface, and everything seems OK. However, when I perform a query in the following fashion: using(entityContext dc = new entityContext()) { int numRows = dc.myTable.Count(); } The query that is generated looks something like this: SELECT `GroupBy1`.`A1` AS `C1` FROM (SELECT Count(1) AS `A1` FROM (SELECT `pricing table`.`a`, `pricing table`.`b`, `pricing table`.`c`, `pricing table`.`d`, `pricing table`.`e`, `pricing table`.`f`, `pricing table`.`g`, `pricing table`.`h`, `pricing table`.`i` FROM `pricing table` AS `pricing table`) AS `Extent1`) AS `GroupBy1` As should be evident, this is an excruciatingly unoptimized query. It is selecting every single row! This is not optimal, nor is it even possible for me to use MySQL + EF at this point. I have tried both the MySQL 6.3.1 [that was fun to install] and DevArt's dotConnect for MySQL and both produce the same results. This table has 1.5 million records.. and takes 6-11s to execute! What am I doing wrong ? Is there any way to optimize this [and other queries] to produce sane code like: SELECT COUNT(*) FROM table ? Generating the same query using SQLServer takes virtually no time and produces sane code. Help! Thanks! Matthew

    Read the article

  • Help me understand entity framework 4 caching for lazy loading

    - by Chris
    I am getting some unexpected behaviour with entity framework 4.0 and I am hoping someone can help me understand this. I am using the northwind database for the purposes of this question. I am also using the default code generator (not poco or self tracking). I am expecting that anytime I query the context for the framework to only make a round trip if I have not already fetched those objects. I do get this behaviour if I turn off lazy loading. Currently in my application I am breifly turning on lazy loading and then turning it back off so I can get the desired behaviour. That pretty much sucks, so please help. Here is a good code example that can demonstrate my problem. Public Sub ManyRoundTrips() context.ContextOptions.LazyLoadingEnabled = True Dim employees As List(Of Employee) = context.Employees.Execute(System.Data.Objects.MergeOption.AppendOnly).ToList() 'makes unnessesary round trip to the database, I just loaded the employees' MessageBox.Show(context.Employees.Where(Function(x) x.EmployeeID < 10).ToList().Count) context.Orders.Execute(System.Data.Objects.MergeOption.AppendOnly) For Each emp As Employee In employees 'makes unnessesary trip to database every time despite orders being pre loaded.' Dim i As Integer = emp.Orders.Count Next End Sub Public Sub OneRoundTrip() context.ContextOptions.LazyLoadingEnabled = True Dim employees As List(Of Employee) = context.Employees.Include("Orders").Execute(System.Data.Objects.MergeOption.AppendOnly).ToList() MessageBox.Show(employees.Where(Function(x) x.EmployeeID < 10).ToList().Count) For Each emp As Employee In employees Dim i As Integer = emp.Orders.Count Next End Sub Why is the first block of code making unnessesary round trips?

    Read the article

  • Entity Framework and stored procedure returning temp table Issues

    - by kaplooeymom
    (Disclaimer - I'm not the database designer. I'm just the poor developer what has to make this work.) There are 17 (at the moment) tables with identical structure - name, address, phone number. Given a phone number, I have to check to see if there's a matching entry in any of the tables, then return that address. So, I created a view to get the list of tables (there's a ref table that holds that info), then I created a stored procedure to create a temp table, using cursors, check each table in the view for the phone number, using sql concatenation. If a record is found, insert it into the temp table. return the rows from the temp table. This all works in straight T-SQL. Now, I'm trying to use Entity Framework 4+ to call the stored procedure. But the function import interface won't generate columns. It says return type = none, and the LINQ code expects an int and won't compile. Any ideas on how to make this work? I know I can move the check tables part to code, if I absolutely have to, but I'd rather have the above method work.

    Read the article

  • Entity Framework 4 overwrite Equals and GetHashCode of an own class property

    - by Zhok
    Hi, I’m using Visual Studio 2010 with .NET 4 and Entity Framework 4. I’m working with POCO Classes and not the EF4 Generator. I need to overwrite the Equals() and GetHashCode() Method but that doesn’t really work. Thought it’s something everybody does but I don’t find anything about the problem Online. When I write my own Classes and Equals Method, I use Equals() of property’s, witch need to be loaded by EF to be filled. Like this: public class Item { public virtual int Id { get; set; } public virtual String Name { get; set; } public virtual List<UserItem> UserItems { get; set; } public virtual ItemType ItemType { get; set; } public override bool Equals(object obj) { Item item = obj as Item; if (obj == null) { return false; } return item.Name.Equals(this.Name) && item.ItemType.Equals(this.ItemType); } public override int GetHashCode() { return this.Name.GetHashCode() ^ this.ItemType.GetHashCode(); } } That Code doesn’t work, the problems are in Equals and GetHashCode where I try to get HashCode or Equal from “ItemType” . Every time I get a NullRefernceException if I try to get data by Linq2Entites. A dirty way to fix it, is to capture the NullReferenceException and return false (by Equals) and return base.GetHashCode() (by GethashCode) but I hope there is a better way to fix this problem. I’ve wrote a little test project, with SQL Script for the DB and POCO Domain, EDMX File and Console Test Main Method. You can download it here: Download

    Read the article

  • .Net Entity objectcontext thread error

    - by Chris Klepeis
    I have an n-layered asp.net application which returns an object from my DAL to the BAL like so: public IEnumerable<SourceKey> Get(SourceKey sk) { var query = from SourceKey in _dataContext.SourceKeys select SourceKey; if (sk.sourceKey1 != null) { query = from SourceKey in query where SourceKey.sourceKey1 == sk.sourceKey1 select SourceKey; } return query.AsEnumerable(); } This result passes through my business layer and hits the UI layer to display to the end users. I do not lazy load to prevent query execution in other layers of my application. I created another function in my DAL to delete objects: public void Delete(SourceKey sk) { try { _dataContext.DeleteObject(sk); _dataContext.SaveChanges(); } catch (Exception ex) { Debug.WriteLine(ex.Message + " " + ex.StackTrace + " " + ex.InnerException); } } When I try to call "Delete" after calling the "Get" function, I receive this error: New transaction is not allowed because there are other threads running in the session This is an ASP.Net app. My DAL contains an entity data model. The class in which I have the above functions share the same _dataContext, which is instantiated in my constructor. My guess is that the reader is still open from the "Get" function and was not closed. How can I close it?

    Read the article

  • Entity Framework Duplicate type name within an assembly (6.1.0)

    - by CodeMilian
    I am not sure what is going on but I keep getting the following exception when doing a query. "Duplicate type name within an assembly." I have not been able to find a solution on the web. I had resolved the issue by removing entity framework from all the projects in the solutions and re-installing using nugget. Then all of the sudden the exception is back. I have verified my table schema over and over and find nothing wrong with. This is the query causing the exception. var BaseQuery = from Users in db.Users join UserInstalls in db.UserTenantInstalls on Users.ID equals UserInstalls.UserID join Installs in db.TenantInstalls on UserInstalls.TenantInstallID equals Installs.ID where Users.Username == Username && Users.Password == Password && Installs.Name == Install select Users; var Query = BaseQuery.Include("UserTenantInstalls.TenantInstall"); return Query.FirstOrDefault(); As I mentioned previously the same query was working before. The data has not changed and the code has not changed.

    Read the article

  • Error while updating Database record with Entity Framework on ASP.NET MVC Page

    - by Rupa
    Hi I have an ASP.NET Page that updates registered User Address Details for a selected record. Below is the Update method that i am calling from Controller. When i am calling ApplyPropertyChanges method, I am getting the below error. Did anyone run into the same error while updating the record with Entity Framework. Appreciate your responses. Error Message: The existing object in the ObjectContext is in the Added state. Changes can only be applied when the existing object is in an unchanged or modified state. My Update Method Code: [HttpPost] public bool UpdateAddressDetail([Bind(Prefix = "RegUser")] AddressDetail regUserAddress, FormCollection formData) { regUserAddress.AD_Id = 3; regUserAddress.LastUpdated = HttpContext.User.Identity.Name; regUserAddress.UpdatedOn = DateTime.Now; regUserAddress.AddressType = ((AddressDetail)Session["CurrentAddress"]).AddressType ?? "Primary"; regUserAddress.Phone = ((AddressDetail)Session["CurrentAddress"]).Phone; regUserAddress.Country = ((AddressDetail)Session["CurrentAddress"]).AddressType ?? "USA"; miEntity.ApplyPropertyChanges(regUserAddress.EntityKey.EntitySetName, regUserAddress); miEntity.SaveChanges(); return true; }

    Read the article

  • When to call Dispose in Entity Framework?

    - by Abdel Olakara
    Hi All, In my application I am making use of Spring.Net for IoC. The service objects are called from the ASP.Net files to perform CRUD operations using these service object. For example, I have CustomerService to do all CRUD operations on Customer table. I use entity framework and the entities are injected .. my question is where do I call the dispose method? As far as I understood from the API documentations, unless I call Dispose() there is no guaranty it will be garbage collected! So where and how do I do it? Example Service Class: public class CustomerService { public ecommEntities entities = {get; set;} public bool AddCustomer(Customer customer) { try { entities.AddToCustomer(customer); entities.SaveChanges(); return true; } catch (Exception e) { log.Error("Error occured during creation of new customer: " + e.Message + e.StackTrace); return false; } } public bool UpdateCustomer(Customer customer) { entities.SaveChanges(); return true; } public bool DeleteCustomer(Customer customer) . . . And I just create an object of CustomerService at the ASP partial class and call the necessary methods. Thanks in advance for the best practice and ideas.. Regards, Abdel Raoof

    Read the article

  • Using SQL dB column as a lock for concurrent operations in Entity Framework

    - by Sid
    We have a long running user operation that is handled by a pool of worker processes. Data input and output is from Azure SQL. The master Azure SQL table structure columns are approximated to [UserId, col1, col2, ... , col N, beingProcessed, lastTimeProcessed ] beingProcessed is boolean and lastTimeProcessed is DateTime. The logic in every worker role is: public void WorkerRoleMain() { while(true) { try { dbContext db = new dbContext(); // Read foreach (UserProfile user in db.UserProfile .Where(u => DateTime.UtcNow.Subtract(u.lastTimeProcessed) > TimeSpan.FromHours(24) & u.beingProcessed == false)) { user.beingProcessed = true; // Modify db.SaveChanges(); // Write // Do some long drawn processing here ... ... ... user.lastTimeProcessed = DateTime.UtcNow; user.beingProcessed = false; db.SaveChanges(); } } catch(Exception ex) { LogException(ex); Sleep(TimeSpan.FromMinutes(5)); } } // while () } With multiple workers processing as above (each with their own Entity Framework layer), in essence beingProcessed is being used a lock for MutEx purposes Question: How can I deal with concurrency issues on the beingProcessed "lock" itself based on the above load? I think read-modify-write operation on the beingProcessed needs to be atomic but I'm open to other strategies. Open to other code refinements too.

    Read the article

  • entity framework vNext wish list

    - by Fred Yang
    I have been intensively studying and use ef4 in my project. I do feel the improvement that it has over version 1. But I found that I have something I cannot get around easily. Here is a list I want it to be better in ef vNext. the model designer should allow multiple view of the same model, so that I don't need cram all my entity into a single view. respect user's manual edit of edmx. Currently, the some database view object simply can not be imported to the model because the designer "smartly" think that the view does not have a primary key, so that I have to manually edit the edmx to correct designer's behavior. But in the next "update from database" task, designer will revert my customization. For now, I simply fallback to manually edit the edmx file at all, or I have to use compare tool to keep the new update, and rollback and put the new update into my old edmx file manually. Designer should be improved to allow default behavior and user's manual control. I want control not to let the designer refresh the change of imported object. support user defined table function. linq is about Composability, stored proc dos not support composability. I wish I could use user defined table function which support this. What are you wishes for EF vNext?

    Read the article

  • Fetching Strategy example in repository pattern with pure POCO Entity framework

    - by Shawn Mclean
    I'm trying to roll out a strategy pattern with entity framework and the repository pattern using a simple example such as User and Post in which a user has many posts. From this answer here, I have the following domain: public interface IUser { public Guid UserId { get; set; } public string UserName { get; set; } public IEnumerable<Post> Posts { get; set; } } Add interfaces to support the roles in which you will use the user. public interface IAddPostsToUser : IUser { public void AddPost(Post post); } Now my repository looks like this: public interface IUserRepository { User Get<TRole>(Guid userId) where TRole : IUser; } Strategy (Where I'm stuck). What do I do with this code? Can I have an example of how to implement this, where do I put this? public interface IFetchingStrategy<TRole> { TRole Fetch(Guid id, IRepository<TRole> role) } My basic problem was what was asked in this question. I'd like to be able to get Users without posts and users with posts using the strategy pattern.

    Read the article

  • How to properly use Object Contexts in Entity Framework using BackgroundWorker

    - by OffApps Cory
    Good day, I am developing using Entity Framework and WPF, and I am encountering some errors and I don't know why. When saving a record (using a BackgroundWorker), I set the entities change tracker to nothing (null), attach the record to a new disposable context, save it, detach, and dispose of the context. Saving a record fires and event in the MainViewModel of the program that the other ViewModels (including the one that is saving) need to refresh their entities to reflect changes. Private Sub _saveRecordWorker_DoWork(ByVal sender As Object, ByVal e As System.ComponentModel.DoWorkEventArgs) Handles _saveRecordWorker.DoWork Using MyContext As New RVShippingEntities Dim MyShipment = CType(ShipmentRecord, IEntityWithChangeTracker) MyShipment.SetChangeTracker(Nothing) MyContext.Attach(MyShipment) MyContext.Detach(ShipmentRecord) End Using End Sub The Refresh background worker is similar, but it has a Do While block to keep it from interfering with the save worker (which doesn't appear to be working; hence the post). When I save (and it subsequently refreshes) I get the following error: The calling thread cannot access this object because a different thread owns it. I thought that with the DoWhile block, it would wait (and when i step through it does) until the save thread finished, and all would be good. But it would seem that something (either the main thread or the save thread) is still doing something that is interfering. Is there a better way of doing this? Am I doing it is a goofy kludgey fashion? Any help would be appreciated. (Apparently Firefox recognized kludgey as a word. Interesting)

    Read the article

  • Best way to transfer an Entity Framework object over the web and back via JSON

    - by AVH
    I've got some MVC code that serializes an EF 3.5 object into an anonymous type for return as a JSON result to an AJAX call on my page. The hurdle I have is that when I send the object back to the server via JSON, (and let the ModelBinder deserialize it for me into my EF type), I have to update it in my Entity Framework context manually. Or at least that's what I'm doing now. It has no EntityKey, so attaching it fails. I end up having to look up the old object and update it property by property. Any ideas around this? Is the solution to pass the EntityKey around with my object? Here's what I have: public void Update(Album album) { using (var db = new BandSitesMasterEntities()) { var albumToUpdate = db.Album.First(x => x.ID == album.ID); albumToUpdate.AlbumTitle = album.AlbumTitle; albumToUpdate.Description = album.Description; albumToUpdate.ReleaseYear = album.ReleaseYear; albumToUpdate.ImageURL = album.ImageURL; albumToUpdate.OtherURL = album.OtherURL; db.SaveChanges(); } } And here's what I'd like to do, or something similar: public void Update(Album album) { using (var db = new BandSitesMasterEntities()) { db.Attach(album) db.SaveChanges(); } }

    Read the article

  • LINQ to Entity: using Contains in the "select" portion throws unexpected error

    - by Chu
    I've got a LINQ query going against an Entity Framework object. Here's a summary of the query: //a list of my allies List<int> allianceMembers = new List<int>() { 1,5,10 }; //query for fleets in my area, including any allies (and mark them as such) var fleets = from af in FleetSource select new Fleet { fleetID = af.fleetID, fleetName = af.fleetName, isAllied = (allianceMembers.Contains(af.userID) ? true : false) }; Basically, what I'm doing is getting a set of fleets. The allianceMembers list contains INTs of all users who are allied with me. I want to set isAllied = true if the fleet's owner is part of that list, and false otherwise. When I do this, I am seeing an exception: "LINQ to Entities does not recognize the method 'Boolean Contains(Int32)' method" I can understand getting this error if I had used the contains in the where portion of the query, but why would I get it in the select? By this point I would assume the query would have executed and returned the results. This little ditty of code does nothing to constrain my data at all. Any tips on how else I can accomplish what I need to with setting the isAllied flag? Thanks

    Read the article

  • Entity Framework autoincrement key

    - by Tommy Ong
    I'm facing an issue of duplicated incremental field on a concurrency scenario. I'm using EF as the ORM tool, attempting to insert an entity with a field that acts as a incremental INT field. Basically this field is called "SequenceNumber", where each new record before insert, will read the database using MAX to get the last SequenceNumber, append +1 to it, and saves the changes. Between the getting of last SequenceNumber and Saving, that's where the concurrency is happening. I'm not using ID for SequenceNumber as it is not a unique constraint, and may reset on certain conditions such as monthly, yearly, etc. InvoiceNumber | SequenceNumber | DateCreated INV00001_08_14 | 1 | 25/08/2014 INV00001_08_14 | 1 | 25/08/2014 <= (concurrency is creating two SeqNo 1) INV00002_08_14 | 2 | 25/08/2014 INV00003_08_14 | 3 | 26/08/2014 INV00004_08_14 | 4 | 27/08/2014 INV00005_08_14 | 5 | 29/08/2014 INV00001_09_14 | 1 | 01/09/2014 <= (sequence number reset) Invoice number is formatted based on the SequenceNumber. After some research I've ended up with these possible solutions, but wanna know the best practice 1) Optimistic Concurrency, locking the table from any reads until the current transaction is completed (not fancy of this idea as I guess performance will be of a great impact?) 2) Create a Stored Procedure solely for this purpose, does select and insert on a single statement as such concurrency is at minimum (would prefer a EF based approach if possible)

    Read the article

  • Foreign key relationships in Entity Framework

    - by Anders Svensson
    I'm trying to add an object created from Entity Data Model classes. I have a table called Users, which has turned into a User EDM class. And I also have a table Pages, which has become a Page EDM class. These tables have a foreign key relationship, so that each page is associated with many users. Now I want to be able to add a page, but I can't get how to do it. I get a nullreference exception on Users below. I'm still rather confused by all this, so I'm sure it's a simple error, but I just can't see how to do it. Also, by the way, the compiler requires that I set PageID in the object initializer, even though this field is set to be an automatic id in the table. Am I doing it right just setting it to 0, expecting it to be updated automatically in the table when saved, or how should I do that? Any help appreciated! The method in question: private Page GetPage(User currentUser) { string url = _request.ServerVariables["url"].ToLower(); var userPages = from p in _context.PageSet where p.Users.UserID == currentUser.UserID select p; var existingPage = userPages.FirstOrDefault(e => e.Url == url); //Could be combined with above, but hard to read? if (existingPage != null) return existingPage; Page page = new Page() { Count = 0, Url = _request.ServerVariables["url"].ToLower(), PageID = 0, //Only initial value, changed later? }; _context.AddToPageSet(page); page.Users.UserID = currentUser.UserID; //Here's the problem... return page; }

    Read the article

< Previous Page | 25 26 27 28 29 30 31 32 33 34 35 36  | Next Page >