Search Results

Search found 139 results on 6 pages for 'dbml'.

Page 5/6 | < Previous Page | 1 2 3 4 5 6  | Next Page >

  • Duplicate a database record with linq

    - by holz
    Is there a way to duplicate a db record with linq to sql in c#? Id [int] IDENTITY(1,1) NOT NULL PRIMARY KEY, [Foo] [nvarchar](255) NOT NULL, [Bar] [numeric](28,12) NOT NULL, ... Given the table above, I would like to duplicate a record (but give it a different id), in a way that new fields added to the DB and the Linq dbml file at a later date will still get duplicated with out having to change that code that duplicates the record. ie I don't want to write newRecord.Foo = currentRecord.Foo; for all of the fields on the table.

    Read the article

  • C# Unit Testing - Generating Mock DataContexts / LINQ -> SQL classes

    - by gav
    Hi All, I am loving the new world that is C#, I've come to a point with my toy programs where I want to start writing some unit tests. My code currently uses a database via a DatabaseDataContext object (*.dbml file), what's the best way to create a mock for this object? Given how easy it is to generate the database LINQ - SQL code and how common a request this must be I'm hoping that VS2010 has built in functionality to help with testing. If I'm way off and this must be done manually could you please enlighten me as to your preferred approach? Many Thanks, Gavin

    Read the article

  • iPhone RSS Reader -- parseXML won't Load some XML feeds

    - by JBMJBM
    I am using the SIMPLE RSS reading example found at http://theappleblog.com/2008/08/04/tutorial-build-a-simple-rss-reader-for-iphone/ It uses parseXML to load the RSS feeds. Here is the problem I am having. For the following RSS feed example, I am having trouble getting it to load the feed. Comes up with an error that it cannot connect. However on my Mac RSS Reader it works fine, so I know the link is good. Any ideas on why it cannot load this particular feed but it can load others fine? http://www.okstate.com/rss.dbml?db_oem_id=200&media=news Thanks.

    Read the article

  • Using Linq to SQL change events with attribute-based mapping

    - by R Mene
    I'm writing a new ASP.NET MVC2 application using Linq to SQL. This application depends on an existing SQL database. I am using attribute-based mapping to map my database fields to my Linq to SQL entities. I also need to make use of Linq to SQL's On[Property]Changed methods so I can perform change-auditing of database tables within my application. Whereas the documentation explains how to do this when using Linq to SQL's ORM and dbml files (i.e. by writing partial classes), it is not clear how to do with when using attribute-based mapping or when using XML-based mapping. It would be very helpful if someone could describe how to do this.

    Read the article

  • ASP.MVC ModelBinding Behaviour

    - by OldBoy
    This one has me stumped, despite the numerous posts on here. The scenario is a basic MVC(2) web application with simple CRUD operations. Whenever the edit form is submitted and the UpdateModel() called, an exception is thrown: System.Data.Linq.ForeignKeyReferenceAlreadyHasValueException was unhandled by user code This occurs against a DropDownList value which is a foreign key on the entity table. However, there is another DropDownList list on the form, representing another foreign key, which does not throw the error (unsurprisingly). Changing the property values manually inside the Edit Action: Recipe recipe = repository.GetRecipe(int.Parse(formValues["recipeid"])); recipe.CategoryId = Convert.ToInt32(formValues["CategoryId"].ToString()); recipe.Page = int.Parse(formValues["Page"].ToString()); recipe.PublicationId=Convert.ToInt32(formValues["PublicationId"].ToString()); Allows the CategoryId and Page properties to be updated, and then the error is thrown on the PublicationId. All of the referential integrity is checked an the same in the db and the dbml. Any light shed on this would be most welcome.

    Read the article

  • How does linq decide between inner & outer joins

    - by user287795
    Hi Usually linq is using an left outer join for its queries but on some cases it decides to use inner join instead. I have a situation where that decision results in wrong results since the second table doesn't always have suitable records and that removes the records from the first table. I'm using a linqdatasource over a dbml where the relevant tables are identical but one holds historical records removed from the first. both have the same primary key. and I'm using a dataloadoption to load both tables at once with out round trips. Would you explain why linq decided to use an inner join here? Thanks

    Read the article

  • DataContext Doesn't Exist in Dynamic Data Project?

    - by davemackey
    This is really annoying...and I know it is something extremely simple... 1. I create a new Dynamic Data project. 2. I add a LINQ-to-SQL class and drag and drop some tables onto the class. 3. I open the global.asax.vb and uncomment the line: DefaultModel.RegisterContext(GetType(YourDataContext), New ContextConfiguration() With {.ScaffoldAllTables = True}) I remove YourDataContext and replace it with the DataContext from my LINQ-to-SQL class: DefaultModel.RegisterContext(GetType(NorthwindDataContext), New ContextConfiguration() With {.ScaffoldAllTables = True}) I then try to debug/build/etc. and receive the following error: Type 'NorthwindDataContext' is not defined Why is it not defined? It seems like its not recognizing I created the DBML file.

    Read the article

  • Dynamic connection for LINQ to SQL DataContext

    - by Steve Clements
    If for some reason you need to specify a specific connection string for a DataContext, you can of course pass the connection string when you initialise you DataContext object.  A common scenario could be a dev/test/stage/live connection string, but in my case its for either a live or archive database.   I however want the connection string to be handled by the DataContext, there are probably lots of different reasons someone would want to do this…but here are mine. I want the same connection string for all instances of DataContext, but I don’t know what it is yet! I prefer the clean code and ease of not using a constructor parameter. The refactoring of using a constructor parameter could be a nightmare.   So my approach is to create a new partial class for the DataContext and handle empty constructor in there. First from within the LINQ to SQL designer I changed the connection property to None.  This will remove the empty constructor code from the auto generated designer.cs file. Right click on the .dbml file, click View Code and a file and class is created for you! You’ll see the new class created in solutions explorer and the file will open. We are going to be playing with constructors so you need to add the inheritance from System.Data.Linq.DataContext public partial class DataClasses1DataContext : System.Data.Linq.DataContext    {    }   Add the empty constructor and I have added a property that will get my connection string, you will have whatever logic you need to decide and get the connection string you require.  In my case I will be hitting a database, but I have omitted that code. public partial class DataClasses1DataContext : System.Data.Linq.DataContext {    // Connection String Keys - stored in web.config    static string LiveConnectionStringKey = "LiveConnectionString";    static string ArchiveConnectionStringKey = "ArchiveConnectionString";      protected static string ConnectionString    {       get       {          if (DoIWantToUseTheLiveConnection) {             return global::System.Configuration.ConfigurationManager.ConnectionStrings[LiveConnectionStringKey].ConnectionString;          }          else {             return global::System.Configuration.ConfigurationManager.ConnectionStrings[ArchiveConnectionStringKey].ConnectionString;          }       }    }      public DataClasses1DataContext() :       base(ConnectionString, mappingSource)    {       OnCreated();    } }   Now when I new up my DataContext, I can just leave the constructor empty and my partial class will decide which one i need to use. Nice, clean code that can be easily refractored and tested.   Share this post :

    Read the article

  • The null value cannot be assigned to a member with type System.Int64 which is a non-nullable value t

    - by BritishDeveloper
    I'm getting the following error in my MVC2 app using Linq to SQL (I am new to both). I am connected to an actual SQL server not weird mdf: System.InvalidOperationException The null value cannot be assigned to a member with type System.Int64 which is a non-nullable value type My SQL table has a column called MessageID. It is BigInt type and has a primary key, NOT NULL and an IDENTITY 1 1, no Default In my dbml designer it has the following declaration for this field: [global::System.Data.Linq.Mapping.ColumnAttribute(Storage="_MessageId", AutoSync=AutoSync.OnInsert, DbType="BigInt NOT NULL IDENTITY", IsPrimaryKey=true, IsDbGenerated=true)] public long MessageId { get { return this._MessageId; } set { if ((this._MessageId != value)) { this.OnMessageIdChanging(value); this.SendPropertyChanging(); this._MessageId = value; this.SendPropertyChanged("MessageId"); this.OnMessageIdChanged(); } } } It keeps telling me that null cannot be assigned - I'm not passing through null! It's a long - it can't even be null! Am I doing something stupid? I can't find a solution anywhere! I made this work by changing the type of this property to Nullable<long> but surely this can't be right? Update: I am using InsertOnSubmit. Simplified code: public ActionResult Create(Message message) { if (ModelState.IsValid) { var db = new MessagingDataContext(); db.Messages.InsertOnSubmit(message); db.SubmitChanges(); //line 93 (where it breaks) } } breaks on SubmitChanges() with the error at the top of this question. Update2: Stack trace: at Read_Object(ObjectMaterializer`1 ) at System.Data.Linq.SqlClient.ObjectReaderCompiler.ObjectReader`2.MoveNext() at System.Linq.Enumerable.FirstOrDefault[TSource](IEnumerable`1 source) at System.Data.Linq.ChangeDirector.StandardChangeDirector.DynamicInsert(TrackedObject item) at System.Data.Linq.ChangeDirector.StandardChangeDirector.Insert(TrackedObject item) at System.Data.Linq.ChangeProcessor.SubmitChanges(ConflictMode failureMode) at System.Data.Linq.DataContext.SubmitChanges(ConflictMode failureMode) at Qanda.Controllers.MessagingController.Ask(Message message) in C:\Qanda\Qanda\Controllers\MessagingController.cs:line 93 Update3: No one knows and I don't have enough clout to offer a bounty! So continued on my ASP.NET blog. Please help!

    Read the article

  • WCF RIA Silverlight deployment issues

    - by Handleman
    It seems the world is awash with people having problems deploying RIA WCF services, and now I'm one too. I've already tried a bunch of things, but to no avail. I need WCF RIA to support a Silverlight 3 application I've built. The short story is, using the new WCF RIA services (Nov 09?) I open VS 2008, create new project (silverlight application), enabling ".NET RIA services". Add new item to web project - Linq2SQL dbml file (from SQL 2005 DB prepared earlier) and compile. I add a new item to the web project - domain service (link the tables I need) and compiled. Using the domain context I "Load" data with a standard RIA get query in the MainPage and add a TextBlock to display returned data. Build & run (cassini) - success. Using VS to publish to IIS on local PC - success. Using VS to publish to test server (IIS6) - browse to location and the Silverlight app loads but Fiddler tells me I've got a 404 on all the the WCF .svc requests. Use Fiddler to "launch IE" on the service request and it's true - 404. I have already run aspnet_regiis, ServiceModelReg and added mime types for .xap, .xaml, .xbap and .svc. I have included the System.Web.Ria and System.Web.DomainServices DLL with copy local true. I need help with either a) a solution b) an approach to find a solution

    Read the article

  • An unhandled exception of type 'System.StackOverflowException' occurred in mscorlib.dll

    - by mazhar
    Ok the thing is that I am using asp.net mvc with linq to sql. I have a scenario where there are two tables group and features with many to many relationship with the third table groupfeatures. I have drag and drop all three table in the dbml file. The thing is that it runs fine with group but when I call the Feature things the above error occured and the compilers stops at this line in ((())). public partial class EgovtDataContext : System.Data.Linq.DataContext { private static System.Data.Linq.Mapping.MappingSource mappingSource = new AttributeMappingSource(); #region Extensibility Method Definitions partial void OnCreated(); partial void InsertGroup(Group instance); partial void UpdateGroup(Group instance); partial void DeleteGroup(Group instance); partial void InsertFeature(Feature instance); partial void UpdateFeature(Feature instance); partial void DeleteFeature(Feature instance); partial void InsertGroupFeature(GroupFeature instance); partial void UpdateGroupFeature(GroupFeature instance); partial void DeleteGroupFeature(GroupFeature instance); #endregion (((public EgovtDataContext() : base(global::System.Configuration.ConfigurationManager.ConnectionStrings["egovtsConnectionString"].ConnectionString, mappingSource)))) The code in both the controller Group and features file is ditto copied. Note the group things are working, the features things are not. FeaturesRepository.cs public IQueryable<Feature> FindAllFeatures() { return db.Features; } FeaturesController.cs FeaturesRepository FeatureRepository = new FeaturesRepository(); public ActionResult Index() { var Feature = FeatureRepository.FindAllFeatures(); return View(Feature); } So what could be wrong?

    Read the article

  • Linq to SQL Problem System.Data.Linq.IdentityManager.StandardIdentityManager.MultiKeyManager

    - by luckyluke
    I have a really tricky thing going up here. My project has around 100 tables and they are all mapped by LINQ. Everything works fine in a dev and test environment. These enviroments are MS Win 2008 r2 servers with SQL 2008 sp1 databases. IIS and SQL are on a different machines. Now on production enviroment which is MS Win 2003 x64 web farm + geoclustered SQL 2008 IT DOES not work. All I get is the exception System.IndexOutOfRangeException: Index was outside the bounds of the array. at System.Data.Linq.IdentityManager.StandardIdentityManager.MultiKeyManager3.TryCreateKeyFr>om Values(Object[] values, MultiKey& k) at System.Data.Linq.IdentityManager.StandardIdentityManager.IdentityCache2.Find(Object[] keyValues) at System.Data.Linq.ChangeProcessor.GetOtherItem(MetaAssociation assoc, Object instance) at System.Data.Linq.ChangeProcessor.BuildEdgeMaps() at System.Data.Linq.ChangeProcessor.SubmitChanges(ConflictMode failureMode) at System.Data.Linq.DataContext.SubmitChanges(ConflictMode failureMode) at ERS.IIMP.Services.ExposuresSrv.Update(Int32 ExpID, Int32 AssID) Services\ExposuresSrv.cs` My question is What the hell. They have precisely the same DBML, the DB has exactly THE SAME structure (when I get the DB from prod to TEST and mount it eveything works just great), the binaries on the WEB Server are the same. I seriously do not know what to do.... Did anyone found that Linq works on one env and does not on the second?? I mam really lost here. I really hope You can help me:)

    Read the article

  • How can I stop an auto-generated Linq to SQL class from loading ALL data?

    - by Gary McGill
    I have an ASP.NET MVC project, much like the NerdDinner tutorial example. (I'm using MVC 2, but followed the NerdDinner tutorial in order to create it). As per the instructions in part 3 of the tutorial, I've created a Linq-to-SQL model of my database by creating a "Linq to SQL Classes" (.dbml) surface, and dropping my database tables onto it. The designer has automatically added relationships between the generated classes based on my database tables. Let's say that my classes are as per the NerdDinner example, so I have Dinner and RSVP tables, where each Dinner record is associated with many RSVP records - hence in the generated classes, the Dinner object has a RSVPs property which is a list of RSVP objects. My problem is this: it appears (and I'd be gladly proved wrong on this) that as soon as I access a Dinner object, it's loading all of the corresponding RSVP objects, even if I don't use the RSVPs member. First question: is this really the default behavior for the generated classes? In my particular situation, the object graph contains many more tables (which have an order of magnitude more records), and so this is disastrous behaviour - I'd be loading tons of data when all I want to do is show the details of a single parent record. Second question: are there any properties exposed through the designer UI that would let me modify this behavior? (I can't find any). Third question: I've seen a description of how to control the loading of related records in a DataContext by using a DataShape object associated with the DataContext. Is that what I'm meant to do, and if so are there any tutorials like the NerdDinner one that would show not only how to do it, but also suggest a 'pattern' for normal use?

    Read the article

  • How can I stop an auto-generated Linq to SQL class from loading ALL data?

    - by Gary McGill
    DUPLICATE of http://stackoverflow.com/questions/2433422/how-can-i-stop-an-auto-generated-linq-to-sql-class-from-loading-all-data post answers there! I have an ASP.NET MVC project, much like the NerdDinner tutorial example. (I'm using MVC 2, but followed the NerdDinner tutorial in order to create it). As per the instructions in part 3 of the tutorial, I've created a Linq-to-SQL model of my database by creating a "Linq to SQL Classes" (.dbml) surface, and dropping my database tables onto it. The designer has automatically added relationships between the generated classes based on my database tables. Let's say that my classes are as per the NerdDinner example, so I have Dinner and RSVP tables, where each Dinner record is associated with many RSVP records - hence in the generated classes, the Dinner object has a RSVPs property which is a list of RSVP objects. My problem is this: it appears (and I'd be gladly proved wrong on this) that as soon as I access a Dinner object, it's loading all of the corresponding RSVP objects, even if I don't use the RSVPs member. First question: is this really the default behavior for the generated classes? In my particular situation, the object graph contains many more tables (which have an order of magnitude more records), and so this is disastrous behaviour - I'd be loading tons of data when all I want to do is show the details of a single parent record. Second question: are there any properties exposed through the designer UI that would let me modify this behavior? (I can't find any). Third question: I've seen a description of how to control the loading of related records in a DataContext by using a DataShape object associated with the DataContext. Is that what I'm meant to do, and if so are there any tutorials like the NerdDinner one that would show not only how to do it, but also suggest a 'pattern' for normal use?

    Read the article

  • How to access a method on a generic datacontext which is only created at runtime

    - by Jeremy Holt
    I'm creating my generic DataContext using only the connectionString in the ctor. I have no issues in retrieving the table using DataContext.GetTable(). However, I need to also be able to retrieve entities of inline table functions. The dbml designer generates public IQueryable<testFunctionResult> testFunction() { return this.CreateMethodCallQuery<testFunctionResult>(this, ((MethodInfo)(MethodInfo.GetCurrentMethod()))); } The question is how do I get the MethodInfo.GetCurrentMethod() when the DataContext has no method called "testFunction", i.e.typeof(DataContext).GetMethod("testFunction") returns null? What I'm trying to achieve is something like: public class UnitofWork<T> { public UnitofWork(string connectionString) { this.DataContext = new DataContext(connectionString); } public UnitofWork(IQueryable<T> tableEntity) { _tableEntity = tableEntity; } public IQueryable<T> TableEntity { get { if (DataContext == null) return _tableEntity; var metaType = DataContext.Mapping.GetMetaType(typeof (T)); if (metaType.IsEntity) _tableEntity = DataContext.GetTable<T>(); else { var s = typeof(T).Name; string methodName = s.Substring(0, s.IndexOf("Result")) + "()"; // the designer automatically affixes "Result" to the type name // Make a method from methodName // _tableEntity = DataContext.CreateMethodCallQuery(DataContext, method, new object[]{}); } return _tableEntity; } set { _tableEntity = value; } } ) Thanks in advance for any insight Jeremy

    Read the article

  • Is this an example of LINQ-to-SQL?

    - by Edward Tanguay
    I made a little WPF application with a SQL CE database. I built the following code with LINQ to get data out of the database, which was surprisingly easy. So I thought "this must be LINQ-to-SQL". Then I did "add item" and added a "LINQ-to-SQL classes" .dbml file, dragged my table onto the Object Relational Designer but it said, "The selected object uses an unsupported data provider." So then I questioned whether or not the following code actually is LINQ-to-SQL, since it indeed allows me to access data from my SQL CE database file, yet officially "LINQ-to-SQL" seems to be unsupported for SQL CE. So is the following "LINQ-to-SQL" or not? using System.Linq; using System.Data.Linq; using System.Data.Linq.Mapping; using System.Windows; namespace TestLinq22 { public partial class Window1 : Window { public Window1() { InitializeComponent(); MainDB db = new MainDB(@"Data Source=App_Data\Main.sdf"); var customers = from c in db.Customers select new {c.FirstName, c.LastName}; TheListBox.ItemsSource = customers; } } [Database(Name = "MainDB")] public class MainDB : DataContext { public MainDB(string connection) : base(connection) { } public Table<Customers> Customers; } [Table(Name = "Customers")] public class Customers { [Column(DbType = "varchar(100)")] public string FirstName; [Column(DbType = "varchar(100)")] public string LastName; } }

    Read the article

  • How to call stored proc from ASP.Net MVC stack via the ORM & return them in json?

    - by melaos
    Hi guys, i'm a total newbie with asp.net mvc and here's my jam: i have a 3 level list box which selection on box A shows options on box B and selection on box B will show the options for box C. I'm trying to do the whole thing in asp.net MVC and what i see is that the nerd dinner tutorial uses the ORM method. so i created a dbml to the database and drag the stored proc inside. i create a datacontext object but i don't quite know how to connect the result from the stored proce which should be multiple rows of data and make it into a json. so i can keep all the json data inside the html page and using jquery i could make the selection process faster. i don't expect the data inside the three boxes to change so often thus i think this method should be quite viable. Questions: So how do i get the stored proc part to return the data as json? i've noticed some tutorial online that the json return result part is at the controller and not at the model end. Why is that?

    Read the article

  • Creating LINQ to SQL Data Models' Data Contexts with ASP.NET MVC

    - by Maxim Z.
    I'm just getting started with ASP.NET MVC, mostly by reading ScottGu's tutorial. To create my database connections, I followed the steps he outlined, which were to create a LINQ-to-SQL dbml model, add in the database tables through the Server Explorer, and finally to create a DataContext class. That last part is the part I'm stuck on. In this class, I'm trying to create methods that work around the exposed data. Following the example in the tutorial, I created this: using System; using System.Collections.Generic; using System.Linq; using System.Web; namespace MySite.Models { public partial class MyDataContext { public List<Post> GetPosts() { return Posts.ToList(); } public Post GetPostById(int id) { return Posts.Single(p => p.ID == id); } } } As you can see, I'm trying to use my Post data table. However, it doesn't recognize the "Posts" part of my code. What am I doing wrong? I have a feeling that my problem is related to my not adding the data tables correctly, but I'm not sure. Thanks in advance.

    Read the article

  • How do I setup Linq to SQL and WCF

    - by Jisaak
    So I'm venturing out into the world of Linq and WCF web services and I can't seem to make the magic happen. I have a VERY basic WCF web service going and I can get my old SqlConnection calls to work and return a DataSet. But I can't/don't know how to get the Linq to SQL queries to work. I'm guessing it might be a permissions problem since I need to connect to the SQL Database with a specific set of credentials but I don't know how I can test if that is the issue. I've tried using both of these connection strings and neither seem to give me a different result. <add name="GeoDataConnectionString" connectionString="Data Source=SQLSERVER;Initial Catalog=GeoData;Integrated Security=True" providerName="System.Data.SqlClient" /> <add name="GeoDataConnectionString" connectionString="Data Source=SQLSERVER;Initial Catalog=GeoData;User ID=domain\userName; Password=blahblah; Trusted_Connection=true" providerName="System.Data.SqlClient" /> Here is the function in my service that does the query and I have the interface add the [OperationContract] public string GetCity(int cityId) { GeoDataContext db = new GeoDataContext(); var city = from c in db.Cities where c.CITY_ID == 30429 select c.DESCRIPTION; return city.ToString(); } The GeoData.dbml only has one simple table in it with a list of city id's and city names. I have also changed the "Serialization Mode" on the DataContext to "Unidirectional" which from what I've read needs to be done for WCF. When I run the service I get this as the return: SELECT [t0].[DESCRIPTION] FROM [dbo].[Cities] AS [t0] WHERE [t0].[CITY_ID] = @p0 Dang, so as I'm writing this I realize that maybe my query is all messed up?

    Read the article

  • ASP.NET MVC Newbie: why isn't my model available when creating a strongly-typed view?

    - by Rax Olgud
    I'm starting with ASP.NET MVC, and working with NerdDinner as reference. I did the following: Created a new project Added a couple of tables Created LINQ to SQL for them Created a new controller My Models directory now contains MyModel.dbml, under which I have MyModel.designer.cs, that contains classes for models relating to both of my tables (let's call them Categories and Products). Now, under my new controller, I would like to create a strongly typed view. So for example I have the following code in my controller (for my application I must work by name, and the "Name" field is unique): public ActionResult Details(string name) { MyModelDataContext db = new MyModelDataContext(); Product user = db.Products.Single(t => t.Name == name); return View(user); } I would like to create a strongly-typed view. So I right-click the line "return View(user)", and choose "Add View...". I click "Create a strongly-typed view". When I click the dropdown of "View data class", I don't see my models, but only: MyProject.Controllers.AccountMembershipService MyProject.Controllers.FormsAuthenticationService What am I missing?

    Read the article

  • DataReader already open when using LINQ

    - by Jamie Dixon
    I've got a static class containing a static field which makes reference to a wrapper object of a DataContext. The DataContext is basically generated by Visual Studio when we created a dbml file & contains methods for each of the stored procedures we have in the DB. Our class basically has a bunch of static methods that fire off each of these stored proc methods & then returns an array based on a LINQ query. Example: public static TwoFieldBarData[] GetAgesReportData(string pct) { return DataContext .BreakdownOfUsersByAge(Constants.USER_MEDICAL_PROFILE_KEY, pct) .Select(x => new TwoFieldBarData(x.DisplayName, x.LeftValue, x.RightValue, x.TotalCount)) .ToArray(); } Every now and then, we get the following error: There is already an open DataReader associated with this Command which must be closed firs This is happening intermittently and I'm curious as to what is going on. My guess is that when there's some lag between one method executing and the next one firing, it's locking up the DataContext and throwing the error. Could this be a case for wrapping each of the DataContext LINQ calls in a lock(){} to obtain exclusivity to that type and ensure other requests are queued?

    Read the article

  • Type or namespace could not be found

    - by Jason Shultz
    I'm using LINQ to SQL to connect my database to my home page. I created my datacontext (named businessModel.dbml) In it I have two tables named Category and Business. In home controller I reference the model and attempt to return to the view the table: var dataContext = new businessModelDataContext(); var business = from b in dataContext.Businesses select b; ViewData["WelcomeMessage"] = "Welcome to Jerome, Arizona!"; ViewData["MottoMessage"] = "Largest Ghost Town in America!"; return View(business); and in the view I have this: <%@ Import Namespace="WelcomeToJerome.Models" %> and <% foreach (business b in (IEnumerable)ViewData.Model) { %> <li><%= b.Title %></li> <% } %> Yet, in the view business is cursed with the red underline and say's that The type or namespace name 'business' could not be found (are you missing a using directive or an assembly reference?) What am I doing wrong? This has had me stumped all afternoon. link to all the code in pastebin: http://pastebin.com/es4RnS2q

    Read the article

  • A many-to-many relation joined disallows intellisense/lookup in joined table

    - by BerggreenDK
    I want to be able to select a product and retrieve all sub-parts(products) within it. My approach is to find the Product id and then retrieve the list of ProductParts with that as a parent and while fetching those, follow the key back to the Product child to get the name and details of each Part. I was hoping to use something similar to: part.linked_product_id.name I have two tables. One for [Product] and and a relation [ProductPart] that has two FK ID's to [Product] Table Product() { int ID; // (PRIMARY, NOT NULL) String Name; ... details removed for overview purpose... } Table ProductPart() { int Product_ID; // FK (linked with relation to Product/parent) int Part_Product_ID; // FK (linked with relation to Product/childen) ... details removed for overview purpose... } I have checked the SQL-diagram and it shows the two relations (both are one to many) and in my DBML they also looks right. Here is my LINQ to SQL snippet that doesnt work for me... wondering why my joins dont work as supposed. FaultySnippet() { ProductDataContext db = new ProductDataContext(); var list = ( from part in db.ProductParts join prod in db.Products on part.Part_Product_ID equals prod.ID where (part.Product_ID == product_ID) select new { Name = part.Part_Product_ID. ?? // <-- NO details from Joined table? ... rest of properties from ProductPart join... I hoped... } ); }

    Read the article

  • Return type from DAL class (Sql ce, Linq to Sql)

    - by bretddog
    Hi, Using VS2008 and Sql CE 3.5, and preferably Linq to Sql. I'm learning database, and unsure about DAL methods return types and how/where to map the data over to my business objects: I don't want direct UI binding. A business object class UserData, and a class UserDataList (Inherits List(Of UserData)), is represented in the database by the table "Users". I use SQL Compact and run SqlMetal which creates dbml/designer.vb file. This gives me a class with a TableAttribute: <Table()> _ Partial Public Class Users I'm unsure how to use this class. Should my business object know about this class, such that the DAL can return the type Users, or List(Of Users) ? So for example the "UserDataService Class" is a part of the DAL, and would have for example the functions GetAll and GetById. Will this be correct : ? Public Class UserDataService Public Function GetAll() As List(Of Users) Dim ctx As New MyDB(connection) Dim q As List(Of Users) = From n In ctx.Users Select n Return q End Function Public Function GetById(ByVal id As Integer) As Users Dim ctx As New MyDB(connection) Dim q As Users = (From n In ctx.Users Where n.UserID = id Select n).Single Return q End Function And then, would I perhaps have a method, say in the UserDataList class, like: Public Class UserDataList Inherits List(Of UserData) Public Sub LoadFromDatabase() Me.clear() Dim database as New UserDataService dim users as List(Of Users) users = database.GetAll() For each u in users dim newUser as new UserData newUser.Id = u.Id newUser.Name = u.Name Me.Add(newUser) Next End Sub End Class Is this a sensible approach? Would appreciate any suggestions/alternatives, as this is my first attempt on a database DAL. cheers!

    Read the article

  • How can I map stored procedure result into a custom class with linq-to-sql?

    - by Remnant
    I have a stored procedure that returns a result set (4 columns x n Rows). The data is based on multiple tables within my database and provides a summary for each department within a corporate. Here is sample: usp_GetDepartmentSummary DeptName EmployeeCount Male Female HR 12 5 7 etc... I am using linq-to-sql to retrieve data from my database (nb - have to use sproc as it is something I have inherited). I would like to call the above sproc and map into a department class: public class Department { public string DeptName {get; set;} public int EmployeeCount {get; set;} public int MaleCount {get; set;} public int FemaleCount {get; set;} } In VS2008, I can drag and drop my sproc onto the methods pane of the linq-to-sql designer. When I examine the designer.cs the return type for this sproc is defined as: ISingleResult<usp_GetDepartmentSummaryResult> What I would like to do is amend this somehow so that it returns a Department type so that I can pass the results of the sproc as a strongly typed view: <% foreach (var dept in Model) { %> <ul> <li class="deptname"><%= dept.DeptName %></li> <li class="deptname"><%= dept.EmployeeCount %></li> etc... Any ideas how to achieve this? NB - I have tried amending the designer.cs and dbml xml file directly but with limited success. I admit to being a little out of my depth when it comes to updating those files directly and I am not sure it is best practice? Would be good to get some diretion. Thanks much

    Read the article

< Previous Page | 1 2 3 4 5 6  | Next Page >