Search Results

Search found 62 results on 3 pages for 'l2s'.

Page 1/3 | 1 2 3  | Next Page >

  • Parallelizing L2S Entity Retrieval

    - by MarkB
    Assuming a typical domain entity approach with SQL Server and a dbml/L2S DAL with a logic layer on top of that: In situations where lazy loading is not an option, I have settled on a convention where getting a list of entities does not also get each item's child entities (no loading), but getting a single entity does (eager loading). Since getting a single entity also gets children, it causes a cascading effect in which each child then gets its children too. This sounds bad, but as long as the model is not too deep, I usually don't see performance problems that outweigh the benefits of the ease of use. So if I want to get a list in which each of the items is fully hydrated with children, I combine the GetList and GetItem methods. So I'll get a list and then loop through it getting each item with the full cascade. Even this is generally acceptable in many of the projects I've worked on - but I have recently encountered situations with larger models and/or more data in which it needs to be more efficient. I've found that partitioning the loop and executing it on multiple threads yields excellent results. In my first experiment with a list of 50 items from one particular project, I did 5 threads of 10 items each and got a 3X improvement in time. Of course, the mileage will vary depending on the project but all else being equal this is clearly a big opportunity. However, before I go further, I was wondering what others have done that have already been through this. What are some good approaches to parallelizing this type of thing?

    Read the article

  • Update a record in L2S and L2E

    - by 5YrsLaterDBA
    I was told in L2S, the code for update and insert are the same, db.InsertOnSubmit(row); db.SubmitChanges(); and L2S will check to see if it is a insert or update and act approprately in the background. Is that true? How about L2E? I tested, looks like in L2E it is not like that. Maybe I did something wrong.

    Read the article

  • Multi-tier applications using L2S, WCF and Base Class

    - by Gena Verdel
    Hi all. One day I decided to build this nice multi-tier application using L2S and WCF. The simplified model is : DataBase-L2S-Wrapper(DTO)-Client Application. The communication between Client and Database is achieved by using Data Transfer Objects which contain entity objects as their properties. abstract public class BaseObject { public virtual IccSystem.iccObjectTypes ObjectICC_Type { get { return IccSystem.iccObjectTypes.unknownType; } } [global::System.Data.Linq.Mapping.ColumnAttribute(Storage = "_ID", AutoSync = AutoSync.OnInsert, DbType = "BigInt NOT NULL IDENTITY", IsPrimaryKey = true, IsDbGenerated = true)] [global::System.Runtime.Serialization.DataMemberAttribute(Order = 1)] public virtual long ID { //get; //set; get { return _ID; } set { _ID = value; } } } [DataContract] public class BaseObjectWrapper<T> where T : BaseObject { #region Fields private T _DBObject; #endregion #region Properties [DataMember] public T Entity { get { return _DBObject; } set { _DBObject = value; } } #endregion } Pretty simple, isn't it?. Here's the catch. Each one of the mapped classes contains ID property itself so I decided to override it like this [global::System.Data.Linq.Mapping.TableAttribute(Name="dbo.Divisions")] [global::System.Runtime.Serialization.DataContractAttribute()] public partial class Division : INotifyPropertyChanging, INotifyPropertyChanged { [global::System.Data.Linq.Mapping.ColumnAttribute(Storage="_ID", AutoSync=AutoSync.OnInsert, DbType="BigInt NOT NULL IDENTITY", IsPrimaryKey=true, IsDbGenerated=true)] [global::System.Runtime.Serialization.DataMemberAttribute(Order=1)] public override long ID { get { return this._ID; } set { if ((this._ID != value)) { this.OnIDChanging(value); this.SendPropertyChanging(); this._ID = value; this.SendPropertyChanged("ID"); this.OnIDChanged(); } } } } Wrapper for division is pretty straightforward as well: public class DivisionWrapper : BaseObjectWrapper<Division> { } It worked pretty well as long as I kept ID values at mapped class and its BaseObject class the same(that's not very good approach, I know, but still) but then this happened: private CentralDC _dc; public bool UpdateDivision(ref DivisionWrapper division) { DivisionWrapper tempWrapper = division; if (division.Entity == null) { return false; } try { Table<Division> table = _dc.Divisions; var q = table.Where(o => o.ID == tempWrapper.Entity.ID); if (q.Count() == 0) { division.Entity._errorMessage = "Unable to locate entity with id " + division.Entity.ID.ToString(); return false; } var realEntity = q.First(); realEntity = division.Entity; _dc.SubmitChanges(); return true; } catch (Exception ex) { division.Entity._errorMessage = ex.Message; return false; } } When trying to enumerate over the in-memory query the following exception occurred: Class member BaseObject.ID is unmapped. Although I'm stating the type and overriding the ID property L2S fails to work. Any suggestions?

    Read the article

  • Arguments of using WCF/OData as access layer instead of EF/L2S/nHibernate directly

    - by Carl Hörberg
    We develop mostly low traffic but highly specialized web applications. Normally we use L2S, EF or nHibernate as access layer and then throws Asp.Net MVC to it and in which for normal crud operations we query the ISession/DataContext directly but for more advanced functions/side effects we put it in a some kind of service layer. Now, i was think about publishing the data through OData (WCF Data Service) and query that from the controllers (or even from jQuery when the a good template engine shows up) and publish the service operations through a WCF service (or as custom methods on the WCF Data Service?). What advantages/disadvantages does this architecture poses? Do I gain something except higher complexity and latency? Better separations of concerns (or is it just a illusion)?

    Read the article

  • Updating an object with L2S with ASP.NET MVC

    - by Paul
    Is there an easier way to update an object with L2S other then doing it property by property? This is what I am doing now: Public ActionResult Edit(Object obj) { var objToUpdate = _repository.Single<Object>(o => o.id = obj.id); objToUpdate.Prop1 = obj.Prob1; objToUpdate.Prop2 = obj.Prop2; ... _repository.SubmitChanges(); } I am hoping there is a way to just say objToUpdate = obj then submit the changes??? Any help on this would be appreciated!

    Read the article

  • Validation L2S question

    - by user158020
    This may be a bit winded because I am new to wpf. I have created a partial class for an entity in my L2S class that is primarily used for validation. It implements the onchanging and onvalidate methods. I am trying to use the MVVM pattern, and in a window/view I have set the datacontext in the xaml: <Window.DataContext> <vm:StartViewModel /> </Window.DataContext> when a user leaves a required field in the view blank, the onchanging event of the partial class is fired when I close the form, not when I save the data. So, if a user leaves the textbox blank, the old value is retained and the onchaging method is fired, but I have no idea how to alert the user of the resulting error. here is my onchanging code in the partial class: partial void Ondocument_titleChanging(string value) { if (value.Length == 0) throw new Exception("Document title is required."); if (value.Length > 256) throw new Exception("Document title cannot be longer than 256 characters."); } throwing an exception doesn't notify the user of the error. it just allows the form to close and rejects the changes to the textbox. hope this makes sense... edit: this example was taken from Scott Guthries article here: http://aspalliance.com/1427_LINQ_to_SQL_Part_5__Binding_UI_using_the_ASPLinqDataSource_Control.5

    Read the article

  • Returning partial address matches and mismatch position using L2S or SQL

    - by peter3
    I need to implement a method that takes an address split up into individual parts and returns any matching items from an address table. If no matches are found, I want to be able to return a value indicating where it failed. Each input param has a corresponding field in the table. The signature would look something like this: List<Address> MatchAddress(string zipCode, string streetName, string houseNumber, string houseLetter, string floor, string appartmentNo, out int mismatchPosition) { // return matching addresses // if none found, return the position where it stopped matching // zipCode is position 0, appartmentNo is position 5 // // an empty param value indicates "don't check" } I know I can construct the method such that I start with all the parameters, execute the query and then remove param by param (from the right side) until either a match is found or I run out of parameters, but can I construct a query that is more effective than that, i.e minimizing the number of calls to the db, maybe even as a single call?

    Read the article

  • Convert SQL with Inner AND Outer Join to L2S

    - by Refracted Paladin
    I need to convert the below Sproc to a Linq query. At the very bottom is what I have so far. For reference the fields behind the "splat"(not my sproc) are ImmunizationID int, HAReviewID int, ImmunizationMaintID int, ImmunizationOther varchar(50), ImmunizationDate smalldatetime, ImmunizationReasonID int The first two are PK and FK, respectively. The other two ints are linke to the Maint Table where there description is stored. That is what I am stuck on, the INNER JOIN AND the LEFT OUTER JOIN Thanks, SELECT tblHAReviewImmunizations.*, tblMaintItem.ItemDescription, tblMaintItem2.ItemDescription as Reason FROM dbo.tblHAReviewImmunizations INNER JOIN dbo.tblMaintItem ON dbo.tblHAReviewImmunizations.ImmunizationMaintID = dbo.tblMaintItem.ItemID LEFT OUTER JOIN dbo.tblMaintItem as tblMaintItem2 ON dbo.tblHAReviewImmunizations.ImmunizationReasonID = tblMaintItem2.ItemID WHERE HAReviewID = @haReviewID My attempt so far -- public static DataTable GetImmunizations(int haReviewID) { using (var context = McpDataContext.Create()) { var currentImmunizations = from haReviewImmunization in context.tblHAReviewImmunizations where haReviewImmunization.HAReviewID == haReviewID join maintItem in context.tblMaintItems on haReviewImmunization.ImmunizationReasonID equals maintItem.ItemID into g from maintItem in g.DefaultIfEmpty() let Immunization = GetImmunizationNameByID( haReviewImmunization.ImmunizationMaintID) select new { haReviewImmunization.ImmunizationDate, haReviewImmunization.ImmunizationOther, Immunization, Reason = maintItem == null ? " " : maintItem.ItemDescription }; return currentImmunizations.CopyLinqToDataTable(); } } private static string GetImmunizationNameByID(int? immunizationID) { using (var context = McpDataContext.Create()) { var domainName = from maintItem in context.tblMaintItems where maintItem.ItemID == immunizationID select maintItem.ItemDescription; return domainName.SingleOrDefault(); } }

    Read the article

  • L2S DataContext out of synch: row not found or changed

    - by awrigley
    The Problem I am getting a number of errors that imply that the DataContext, or rather, the way I am using the DataContext is getting out of synch. The error occurs on db.SubmitChanges() where db is my DataContext instance. The error is: Row not found or changed. The problem only occurs intermitently, for example, adding a row then deleting it. If I stop the dev server and restart, the added row is there and I can delete it no problem. Ie, it seems that the problem is related to the DataContext losing track of the rows that have been added. IMPORTANT: Before anyone votes to close this thread, on the basis of it being a duplicate, I have checked the sql server profiler and there is no "Where 0 = 1" in the SQL. I have also recreated the dbml file, so am satisfied that the database schema is in synch with the schema represented by the dbml file. Ie, no cases of mismatched nullable/not nullable columns, etc. My Diagnosis (for what it is worth): It seems to be a problem related to how I am using the DataContext. I am new to MVC, Repositories and Services patterns, so suspect that I have wired things up wrong. The Setup Simple eLearning app in its early stages. Pupils need to be able to add and delete courses (Courses table) to their UserCourses. To do this, I have a service that gets a specific DataContext instance Dependency Injected into its constructor. Service Class Constructor: public class SqlPupilBlockService : IPupilBlockService { DataContext db; public SqlPupilBlockService(DataContext db) { this.db = db; CoursesRepository = new SqlRepository<Course>(db); UserCoursesRepository = new SqlRepository<UserCourse>(db); } // Etc, etc } The CoursesRepository and UserCoursesRepository are both private properties of the service class that are of Type IRepository (just a simple generic repository interface). Sql Respoitory Code: public class SqlRepository<T> : IRepository<T> where T : class { DataContext db; public SqlRepository(DataContext db) { this.db = db; } #region IRepository<T> Members public IQueryable<T> Query { get { return db.GetTable<T>(); } } public List<T> FetchAll() { return Query.ToList(); } public void Add(T entity) { db.GetTable<T>().InsertOnSubmit(entity); } public void Delete(T entity) { db.GetTable<T>().DeleteOnSubmit(entity); } public void Save() { db.SubmitChanges(); } #endregion } The two methods for adding and deleting UserCourses are: Service Methods for Adding and Deleting UserCourses: public void AddUserCourse(int courseId) { UserCourse uc = new UserCourse(); uc.IdCourse = courseId; uc.IdUser = UserId; uc.DateCreated = DateTime.Now; uc.DateAmended = DateTime.Now; uc.Role = "Pupil"; uc.CourseNotes = string.Empty; uc.ActiveStepIndex = 0; UserCoursesRepository.Add(uc); UserCoursesRepository.Save(); } public void DeleteUserCourse(int courseId) { var uc = (UserCoursesRepository.Query.Where(x => x.IdUser == UserId && x.IdCourse == courseId)).Single(); UserCoursesRepository.Delete(uc); UserCoursesRepository.Save(); } Ajax I am using Ajax via Ajax.BeginForm I don't think that is relevant. ASP.NET MVC 3 I am using mvc3, but don't think that is relevant: the errors are related to model code.

    Read the article

  • Repository Pattern: SaveOrUpdate() in Entity Framework and L2S

    - by JMSA
    These web articles uses separate Save() and Update() methods in the repository pattern. I am using repository pattern. How can I write a SaveOrUpdate() method in Entity Framework with the help of ObjectContext and in Linq-To-SQL with the help of DataContext? That is, how can I write a single method that shall do both save and update job?

    Read the article

  • Dataset and SQLCe in .net 4

    - by Tyler Edwards
    I'm trying to build a SQLCe table structure dynamically using a dataset as the temporary table structure... Is there a SqlConnection string that will work with SqlCe? There used to be a SqlCeConnection...but I don't find that in the 4.0 framework? Has something replaced this? If the answer is L2S or Entity Framework...can I add columns to SqlCe tables at runtime? If so...how?

    Read the article

  • Which .NET data provider?

    - by worlds-apart89
    I am new to database programming, so I'd like help getting on the right track. I have read that there are Microsoft-defined and third-party data providers for data access. MSDN has information on data providers for SQL Server, OLE DB, ODBC, Oracle, as well as the EntityClient provider (Entity Framework). Which data provider is today's hottest, most-widely used model? Which one is the future? Also, I have seen Linq to SQL tutorials, but what category does L2S fall into?

    Read the article

  • Why should I use Entity Framework over Linq2SQL ...

    - by Refracted Paladin
    To be clear, I am not asking for a side by side comparision which has already been asked Ad Nauseum here on SO. I am also Not asking if Linq2Sql is dead as I don't care. What I am asking is this.... I am building internal apps only for a non-profit organization. I am the only developer on staff. We ALWAYS use SQL Server as our Database backend. I design and build the Databases as well. I have used L2S successfully a couple of times already. Taking all this into consideration can someone offer me a compelling reason to use EF instead of L2S? I was at Code Camp this weekend and after an hour long demonstration on EF, all of which I could have done in L2S, I asked this same question. The speakers answer was, "L2S is dead..." Very well then! NOT! (see here) I understand EF is what MS WANTS us to use in the future(see here) and that it offers many more customization options. What I can't figure out is if any of that should, or does, matter for me in this environment. One particular issue we have here is that I inherited the Core App which was built on 4 different SQL Data bases. L2S has great difficulty with this but when I asked the aforementioned speaker if EF would help me in this regard he said "No!"

    Read the article

  • Why use Entity Framework over Linq2SQL ...

    - by Refracted Paladin
    To be clear, I am not asking for a side by side comparision which has already been asked Ad Nauseum here on SO. I am also Not asking if Linq2Sql is dead as I don't care. What I am asking is this.... I am building internal apps only for a non-profit organization. I am the only developer on staff. We ALWAYS use SQL Server as our Database backend. I design and build the Databases as well. I have used L2S successfully a couple of times already. Taking all this into consideration can someone offer me a compelling reason to use EF instead of L2S? I was at Code Camp this weekend and after an hour long demonstration on EF, all of which I could have done in L2S, I asked this same question. The speakers answer was, "L2S is dead..." Very well then! NOT! (see here) I understand EF is what MS WANTS us to use in the future(see here) and that it offers many more customization options. What I can't figure out is if any of that should, or does, matter for me in this environment. One particular issue we have here is that I inherited the Core App which was built on 4 different SQL Data bases. L2S has great difficulty with this but when I asked the aforementioned speaker if EF would help me in this regard he said "No!"

    Read the article

  • Why use Entity Framework over Linq2SQL if...

    - by Refracted Paladin
    To be clear, I am not asking for a side by side comparision which has already been asked Ad Nauseum here on SO. I am also Not asking if Linq2Sql is dead as I don't care. What I am asking is this.... I am building internal apps only for a non-profit organization. I am the only developer on staff. We ALWAYS use SQL Server as our Database backend. I design and build the Databases as well. I have used L2S successfully a couple of times already. Taking all this into consideration can someone offer me a compelling reason that I should use EF instead of L2S? I was at Code Camp this weekend and after an hour long demonstration on EF, all of which I could have done in L2S, I asked this same question. The speakers answer was, "L2S is dead..." Very well then! NOT! (see here) I understand EF is what MS WANTS us to use in the future(see here) and that it offers many more customization options. What I can't figure out is if any of that should, or does, matter for me in this environment. One particular issue we have here is that I inherited the Core App which was built on 4 different SQL Data bases. L2S has great difficulty with this but when I asked the aforementioned speaker if EF would help me in this regard he said "No!"

    Read the article

  • Can LINQ-to-SQL omit unspecified columns on insert so a database default value is used?

    - by Todd Ropog
    I have a non-nullable database column which has a default value set. When inserting a row, sometimes a value is specified for the column, sometimes one is not. This works fine in TSQL when the column is omitted. For example, given the following table: CREATE TABLE [dbo].[Table1]( [id] [int] IDENTITY(1,1) NOT NULL, [col1] [nvarchar](50) NOT NULL, [col2] [nvarchar](50) NULL, CONSTRAINT [PK_Table1] PRIMARY KEY CLUSTERED ([id] ASC) ) GO ALTER TABLE [dbo].[Table1] ADD CONSTRAINT [DF_Table1_col1] DEFAULT ('DB default') FOR [col1] The following two statements will work: INSERT INTO Table1 (col1, col2) VALUES ('test value', '') INSERT INTO Table1 (col2) VALUES ('') In the second statement, the default value is used for col1. The problem I have is when using LINQ-to-SQL (L2S) with a table like this. I want to produce the same behavior, but I can't figure out how to make L2S do that. I want to be able to run the following code and have the first row get the value I specify and the second row get the default value from the database: var context = new DataClasses1DataContext(); var row1 = new Table1 { col1 = "test value", col2 = "" }; context.Table1s.InsertOnSubmit(row1); context.SubmitChanges(); var row2 = new Table1 { col2 = "" }; context.Table1s.InsertOnSubmit(row2); context.SubmitChanges(); If the Auto Generated Value property of col1 is False, the first row is created as desired, but the second row fails with a null error on col1. If Auto Generated Value is True, both rows are created with the default value from the database. I've tried various combinations of Auto Generated Value, Auto-Sync and Nullable, but nothing I've tried gives the behavior I want. L2S does not omit the column from the insert statement when no value is specified. Instead it does something like this: INSERT INTO Table1 (col1, col2) VALUES (null, '') ...which of course causes a null error on col1. Is there some way to get L2S to omit a column from the insert statement if no value is given? Or is there some other way to get the behavior I want? I need the default value at the database level because not all row inserts are done via L2S, and in some cases the default value is a little more complex than a hard coded value (e.g. creating the default based on another field) so I'd rather avoid duplicating that logic.

    Read the article

  • Linq to SQl over WCF Timesout after several calls

    - by Redeemed1
    I have a L2S Repository class which instantiates the L2S DataContext in its constructor. The repository is instantiated at run time (using Unity) in a service hosted in IIS with WCF. When I run up the client MVC applicaton the calls to the backend WCF service work for a while and then timeout. I suspected perhaps a database issue as I was depending on IIS garbage collection to dispose of unused DataContext instances in the IIS host but when I checked the characteristics of the problem I notice the following: The client makes the call to WCF but the WCF service does not respond. Next, the client times out Some time later (several minutes) the service actually executes the request by instantiating the repository and servicing the call. I have checked both client and server traces logs and only the client shows WCF errors (the timeout error). Where should I look? Is it something in WCF or is L2S possibly blocking with unfreed conenctions, resources etc.? Many thanks Brian

    Read the article

  • A better UPDATE method in LINQ to SQL

    - by Refracted Paladin
    The below is a typical, for me, Update method in L2S. I am still fairly new to a lot of this(L2S & business app development) but this just FEELs wrong. Like there MUST be a smarter way of doing this. Unfortunately, I am having trouble visualizing it and am hoping someone can provide an example or point me in the right direction. To take a stab in the dark, would I have a Person Object that has all these fields as Properties? Then what, though? Is that redundant since L2S already mapped my Person Table to a Class? Is this just 'how it goes', that you eventually end up passing 30 parameters(or MORE) to an UPDATE statement at some point? For reference, this is a business app using C#, WinForms, .Net 3.5, and L2S over SQL 2005 Standard. Here is a typical Update Call for me. This is in a file(BLLConnect.cs) with other CRUD methods. Connect is the name of the DB that holds tblPerson When a user clicks save() this is what is eventually called with all of these fields having, potentially, been updated-- public static void UpdatePerson(int personID, string userID, string titleID, string firstName, string middleName, string lastName, string suffixID, string ssn, char gender, DateTime? birthDate, DateTime? deathDate, string driversLicenseNumber, string driversLicenseStateID, string primaryRaceID, string secondaryRaceID, bool hispanicOrigin, bool citizenFlag, bool veteranFlag, short ? residencyCountyID, short? responsibilityCountyID, string emailAddress, string maritalStatusID) { using (var context = ConnectDataContext.Create()) { var personToUpdate = (from person in context.tblPersons where person.PersonID == personID select person).Single(); personToUpdate.TitleID = titleID; personToUpdate.FirstName = firstName; personToUpdate.MiddleName = middleName; personToUpdate.LastName = lastName; personToUpdate.SuffixID = suffixID; personToUpdate.SSN = ssn; personToUpdate.Gender = gender; personToUpdate.BirthDate = birthDate; personToUpdate.DeathDate = deathDate; personToUpdate.DriversLicenseNumber = driversLicenseNumber; personToUpdate.DriversLicenseStateID = driversLicenseStateID; personToUpdate.PrimaryRaceID = primaryRaceID; personToUpdate.SecondaryRaceID = secondaryRaceID; personToUpdate.HispanicOriginFlag = hispanicOrigin; personToUpdate.CitizenFlag = citizenFlag; personToUpdate.VeteranFlag = veteranFlag; personToUpdate.ResidencyCountyID = residencyCountyID; personToUpdate.ResponsibilityCountyID = responsibilityCountyID; personToUpdate.EmailAddress = emailAddress; personToUpdate.MaritalStatusID = maritalStatusID; personToUpdate.UpdateUserID = userID; personToUpdate.UpdateDateTime = DateTime.Now; context.SubmitChanges(); } }

    Read the article

  • How to prevent linq-to-sql designer undo my changing

    - by anonim.developer
    Dear All, Thanks for your attention in advance, I’ve met an issue with LINQ-2-SQL designer in VS 2008 SP1 which has made me CRAZY. I use Linq2sql as my DAL. It seems Linq2sql speeds up coding in the first step but lots of issues arise in feature specifically with table or object inheritance. In this case I have a class Entity that all other entity classes generated by Linq2sql designer inherit from. public abstract class Entity { public virtual Guid ID { get; protected set; } } public partial class User : monius.Data.Entity { } And the following generated by L2S designer (DataModel.designer.cs) [Column(Storage = "_ID", AutoSync = AutoSync.OnInsert, DbType = "UniqueIdentifier NOT NULL", IsPrimaryKey = true, IsDbGenerated = true, UpdateCheck = UpdateCheck.Never)] [DataMember(Order = 1)] public System.Guid ID { get { return this._ID; } set { if ((this._ID != value)) { this.OnIDChanging(value); this.SendPropertyChanging(); this._ID = value; this.SendPropertyChanged("ID"); this.OnIDChanged(); } } } When I compile the code VS warns me that Warning 1 'User.ID' hides inherited member 'Entity.ID'. To make the current member override that mplementation, add the override keyword. Otherwise add the new keyword. That warning is obvious and I have to change the code generated by L2S designer (DataModel.designer.cs) to […] public override System.Guid ID { … protected set … } And the code compiled with no error or warning and everyone is happy. But that is not the end of story. As soon as I made changes to entities of the diagram (dbml) or even I open dbml file to view it, any change manually I made to designer has been vanished and POOF! Redo AGAIN. That is a painful job. Now I wonder if there is a way to force L2S designer not changing portions of auto-generated code. I’ll be appreciated if someone kindly helps me with this issue.

    Read the article

  • Finally! Entity Framework working in fully disconnected N-tier web app

    - by oazabir
    Entity Framework was supposed to solve the problem of Linq to SQL, which requires endless hacks to make it work in n-tier world. Not only did Entity Framework solve none of the L2S problems, but also it made it even more difficult to use and hack it for n-tier scenarios. It’s somehow half way between a fully disconnected ORM and a fully connected ORM like Linq to SQL. Some useful features of Linq to SQL are gone – like automatic deferred loading. If you try to do simple select with join, insert, update, delete in a disconnected architecture, you will realize not only you need to make fundamental changes from the top layer to the very bottom layer, but also endless hacks in basic CRUD operations. I will show you in this article how I have  added custom CRUD functions on top of EF’s ObjectContext to make it finally work well in a fully disconnected N-tier web application (my open source Web 2.0 AJAX portal – Dropthings) and how I have produced a 100% unit testable fully n-tier compliant data access layerfollowing the repository pattern. http://www.codeproject.com/KB/linq/ef.aspx In .NET 4.0, most of the problems are solved, but not all. So, you should read this article even if you are coding in .NET 4.0. Moreover, there’s enough insight here to help you troubleshoot EF related problems. You might think “Why bother using EF when Linq to SQL is doing good enough for me.” Linq to SQL is not going to get any innovation from Microsoft anymore. Entity Framework is the future of persistence layer in .NET framework. All the innovations are happening in EF world only, which is frustrating. There’s a big jump on EF 4.0. So, you should plan to migrate your L2S projects to EF soon.

    Read the article

  • How do I get Linq-to-SQL to refresh its local copy of a database record?

    - by Gary McGill
    Suppose I have an Orders table in my database and a corresponding model class generated by the VS2008 "Linq to SQL Classes" designer. Suppose I also have a stored procedure (ProcessOrder) in my database that I use to do some processing on an order record. If I do the following: var order = dataContext.Orders.Where(o => o.id == orderId).First(); // More code here dataContext.ProcessOrder(orderId); order.Status = "PROCESSED"; dataContext.SubmitChanges(); ...then I'll get a concurrency violation if the ProcessOrder stored proc has modified the order (which is of course very likely), because L2S will detect that the order record has changed, and will fail to submit the changes to that order. That's all fairly logical, but what if I want to update the order record after calling the stored proc? How do I tell L2S to forget about its cached copy and refresh it from the DB?

    Read the article

  • Error in Using Dynamic Data Entities WebSite in VS2012

    - by amin behzadi
    I decided to use Dynamic Data Entities website in vs2012. So, I created this website,then added App_Code directory and added a new edmx to it and named it myDB.edmx. After that I uncommented the code line in global.asax which registers the entity context : DefaultModel.RegisterContext(typeof(myDBEntities), new ContextConfiguration() { ScaffoldAllTables = true }); But when I run the website this error occurs : The context type 'myDBEntities' is not supported. how can I fix it? p.s: You now there are some differences between using L2S by Dynamic Data L2S website AND using entity framework by Dynamic Data Entities website.

    Read the article

  • RIA Services: Inserting multiple presentation-model objects

    - by nlawalker
    I'm sharing data via RIA services using a presentation model on top of LINQ to SQL classes. On the Silverlight client, I created a couple of new entities (album and artist), associated them with each other (by either adding the album to the artist's album collection, or setting the Artist property on the album - either one works), added them to the context, and submitted changes. On the server, I get two separate Insert calls - one for the album and one for the artist. These entitites are new so their ID values are both set to the default int value (0 - keep in mind that depending on my DB, this could be a valid ID in the DB) because as far as I know you don't set IDs for new entities on the client. This all would work fine if I was transferring the LINQ to SQL classes via my RIA services, because even though the Album insert includes the Artist and the Artist insert includes the Album, both are Entities and the L2S context recognizes them. However, with my custom presentation model objects, I need to convert them back to the LINQ to SQL classes maintaining the associations in the process so they can be added to the L2S context. Put simply, as far as I can tell, this is impossible. Each entity gets its own Insert call, but there's no way you can just insert the one entity because without IDs the associations are lost. If the database used GUID identifiers it would be a different story because I could set those on the client. Is this possible, or should I be pursuing another design?

    Read the article

  • Can't get DataGridView to refresh over Linq to SQL (WinForm)

    - by GringoFrenzy
    Very strange situation here: I'm using L2S to populate a DataGridView. Code follows: private void RefreshUserGrid() { var UserQuery = from userRecord in this.DataContext.tblUsers orderby userRecord.DisplayName select userRecord; UsersGridView.DataSource = UserQuery; //I have also tried //this.UserBindingSource.DataSource = UserQuery; //UsersGridView.Datasource = UserBindingSource; UsersGridView.Columns[0].Visible = false; } Whenever I use L2S to Add/Delete records from the database, the GridView refreshes perfectly well. However, if someone is editing the grid and makes a mistake, I want them to be able to hit a refresh button and have their mistakes erased by reloading from the datasource. For the life of me, I can't get it to work. The code I am currently using on my refresh button is this: private void button1_Click(object sender, EventArgs e) { this.DataContext.Refresh(RefreshMode.OverwriteCurrentValues); RefreshUserGrid(); } But the damn GridView remains unaffected. All that happens is the selected row becomes unselected. I have tried .Refresh(), .Invalidate(), I've tried changing the DataSource to NULL and back again (all suggestions from similar posts here)....none of it works. The only time the Grid refreshes is if I restart the app. I must be missing something fundamental, but I'm totally stumped and so are my colleagues. Any ideas? Thanks!

    Read the article

1 2 3  | Next Page >