Search Results

Search found 783 results on 32 pages for 'datacontext'.

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

  • LINQ TO SQL error: An attempt has been made to Attach or Add an entity that is not new...

    - by Collin Estes
    "An attempt has been made to Attach or Add an entity that is not new, perhaps having been loaded from another DataContext. This is not supported." I have scene a lot of solutions dealing with the Attach() method but I'm just trying to add in a new record. Not sure what is going on. Here is my code, It is failing on the star'd line.: try { LINQDataContext datacontext = new LINQDataContext(); TrackableItem ti = datacontext.TrackableItems.FirstOrDefault(_t => _t.pkId == obj.fkTrackableItemId); arcTrackableItem ati = new arcTrackableItem(); ati.barcode = ti.barcode; ati.dashNumber = ti.dashNumber; ati.dateDown = ti.dateDown; ati.dateUp = ti.dateUp; ati.fkItemStatusId = ti.fkItemStatusId; ati.fkItemTypeId = ti.fkItemTypeId; ati.partNumber = ti.partNumber; ati.serialNumber = ti.serialNumber; ati.archiveDate = DateTime.Now; datacontext.arcTrackableItems.InsertOnSubmit(ati); datacontext.SubmitChanges(); arcPWR aItem = new arcPWR(); aItem.comments = obj.comments; aItem.fkTrackableItemId = ati.pkId; aItem.fkPWRStatusId = obj.fkPWRStatusId; aItem.PwrStatus = obj.PwrStatus; **datacontext.arcPWRs.InsertOnSubmit(aItem);** datacontext.SubmitChanges();

    Read the article

  • IoC and dataContext disposing in asp.net mvc 2 application

    - by zerkms
    I have the Global.asax like the code below: public class MvcApplication : System.Web.HttpApplication { public static void RegisterRoutes(RouteCollection routes) { // .... } protected void Application_Start() { AreaRegistration.RegisterAllAreas(); RegisterRoutes(RouteTable.Routes); ControllerBuilder.Current.SetControllerFactory(typeof(IOCControllerFactory)); } } public class IOCControllerFactory : DefaultControllerFactory { private readonly IKernel kernel; public IOCControllerFactory() { kernel = new StandardKernel(new NanocrmContainer()); } protected override IController GetControllerInstance(RequestContext requestContext, Type controllerType) { if (controllerType == null) return base.GetControllerInstance(requestContext, controllerType); var controller = kernel.TryGet(controllerType) as IController; if (controller == null) return base.GetControllerInstance(requestContext, controllerType); var standartController = controller as Controller; if (standartController is IIoCController) ((IIoCController)standartController).SetIoc(kernel); return standartController; } class NanocrmContainer : Ninject.Modules.NinjectModule { public override void Load() { // ... Bind<DomainModel.Entities.db>().ToSelf().InRequestScope().WithConstructorArgument("connection", "Data Source=lims;Initial Catalog=nanocrm;Persist Security Info=True;User ID=***;Password=***"); } } } In this case if somewhere it is the class, defined like: public class UserRepository : IUserRepository { private db dataContext; private IUserGroupRepository userGroupRepository; public UserRepository(db dataContext, IUserGroupRepository userGroupRepository) { this.dataContext = dataContext; this.userGroupRepository = userGroupRepository; } } then the dataContext instance is created (if no one was created in this request scope) by Ninject. So the trouble now is - where to invoke dataContext method .Dispose()?

    Read the article

  • "Attach or Add an entity that is not new...loaded from another DataContext. This is not supported."

    - by sah302
    Similar error as other questions, but not quite the same, I am not trying to attach anything. What I am trying to do is insert a new row into a linking table, specifically UserAccomplishment. Relations are set in LINQ to User and Accomplishment Tables. I have a generic insert function: Public Function insertRow(ByVal entity As ImplementationType) As Boolean If entity IsNot Nothing Then Dim lcfdatacontext As New LCFDataContext() Try lcfdatacontext.GetTable(Of ImplementationType)().InsertOnSubmit(entity) lcfdatacontext.SubmitChanges() lcfdatacontext.Dispose() Return True Catch ex As Exception Return False End Try Else Return False End If End Function If you try and give UserAccomplishment the two appropriate objects this will naturally crap out if either the User or Accomplishment already exist. It only works when both user and accomplishment don't exist. I expected this behavior. What does work is simply giving the userAccomplishment object a user.id and accomplishment.id and populating the rest of the fields. This works but is kind of awkward to use in my app, it would be much easier to simply pass in both objects and have it work out what already exists and what doesn't. Okay so I made the following (please ignore the fact that this is horribly inefficient because I know it is): Public Class UserAccomplishmentDao Inherits EntityDao(Of UserAccomplishment) Public Function insertLinkerObjectRow(ByVal userAccomplishment As UserAccomplishment) Dim insertSuccess As Boolean = False If Not userAccomplishment Is Nothing Then Dim userDao As New UserDao() Dim accomplishmentDao As New AccomplishmentDao() Dim user As New User() Dim accomplishment As New Accomplishment() 'see if either object already exists in db' user = userDao.getOneByValueOfProperty("Id", userAccomplishment.User.Id) accomplishment = accomplishmentDao.getOneByValueOfProperty("Id", userAccomplishment.Accomplishment.Id) If user Is Nothing And accomplishment Is Nothing Then 'neither the user or the accomplishment exist, both are new so insert them both, typical insert' insertSuccess = Me.insertRow(userAccomplishment) ElseIf user Is Nothing And Not accomplishment Is Nothing Then 'user is new, accomplishment is not new, so just insert the user, and the relation in userAccomplishment' Dim userWithExistingAccomplishment As New UserAccomplishment(userAccomplishment.User, userAccomplishment.Accomplishment.Id, userAccomplishment.LastUpdatedBy) insertSuccess = Me.insertRow(userWithExistingAccomplishment) ElseIf Not user Is Nothing And accomplishment Is Nothing Then 'user is not new, accomplishment is new, so just insert the accomplishment, and the relation in userAccomplishment' Dim existingUserWithAccomplishment As New UserAccomplishment(userAccomplishment.UserId, userAccomplishment.Accomplishment, userAccomplishment.LastUpdatedBy) insertSuccess = Me.insertRow(existingUserWithAccomplishment) Else 'both are not new, just add the relation' Dim userAccomplishmentBothExist As New UserAccomplishment(userAccomplishment.User.Id, userAccomplishment.Accomplishment.Id, userAccomplishment.LastUpdatedBy) insertSuccess = Me.insertRow(userAccomplishmentBothExist) End If End If Return insertSuccess End Function End Class Alright, here I basically check if the supplied user and accomplishment already exists in the db, and if so call an appropriate constructor that will leave whatever already exists empty, but supply the rest of the information so the insert can succeed. However, upon trying an insert: Dim result As Boolean = Me.userAccomplishmentDao.insertLinkerObjectRow(userAccomplishment) In which the user already exists, but the accomplishment does not (the 99% typical scenario) I get the error: "An attempt has been made to Attach or Add an entity that is not new, perhaps having been loaded from another DataContext. This is not supported." I have debugged this multiple times now and am not sure why this is occuring, if either User or Accomplishment exist, I am not including it in the final object to try to insert. So nothing appears to be attempted to be added. Even in debug, upon insert, the object was set to empty. So the accomplishment is new and the user is empty. 1) Why is it still saying that and how can I fix it ..using my current structure 2) Pre-emptive 'use repository pattern answers' - I know this way kind of sucks in general and I should be using the repository pattern. However, I can't use that in the current project because I don't have time to refactor that due to my non existence knowledge of it and time constraints. The usage of the app is going to so small that the inefficient use of datacontext's and what have you won't matter so much. I can refactor it once it's up and running, but for now I just need to 'push through' with my current structure. Edit: I also just tested this when having both already exists, and only insert each object's IDs into the table, that works. So I guess I could manually insert whichever object doesn't exist as a single insert, then put the ids only into the linking table, but I still don't know why when one object exists, and I make it empty, it doens't work.

    Read the article

  • Binding Listbox ItemsSource to property of ViewModel in DataContext in WPF

    - by joshperry
    I have a simple ViewModel like: public class MainViewModel { public MainViewModel() { // Fill collection from DB here... } public ObservableCollection<Projects> ProjectList { get; set; } } I set the window's DataContext to a new instance of that ViewModel in the constructor: public MainWindow() { this.DataContext = new MainViewModel(); } Then in the Xaml I am attempting to bind the ItemsSource of a ListBox to that ProjectList property. Binding just ItemsSource like so doesn't work: <ListBox ItemsSource="{Binding ProjectList}" ItemTemplate="..." /> But if I first rebase the DataContext this works: <ListBox DataContext="{Binding ProjectList}" ItemsSource="{Binding}" ItemTemplate="..." /> Shouldn't the first method work properly? What am I doing wrong?

    Read the article

  • Binding property to Silverlight dependency property independent of DataContext

    - by Simon_Weaver
    I'm trying to make an Address control that has an IsReadOnly property, which will make every TextBox inside read only when set to true. <my:AddressControl Grid.Column="1" Margin="5" IsReadOnly="True"/> I've managed to do this just fine with a dependency property and it works. Here's a simple class with the dependency property declared : public partial class AddressControl : UserControl { public AddressControl() { InitializeComponent(); this.DataContext = this; } public static readonly DependencyProperty IsReadOnlyProperty = DependencyProperty.Register("IsReadOnly", typeof(bool), typeof(AddressControl), null); public bool IsReadOnly { get { return (bool)GetValue(IsReadOnlyProperty); } set { SetValue(IsReadOnlyProperty, value); } } } In the XAML for this codebehind file I have a Textbox for each address line: <TextBox IsReadOnly="{Binding IsReadOnly}" Text="{Binding City, Mode=TwoWay}"/> <TextBox IsReadOnly="{Binding IsReadOnly}" Text="{Binding State, Mode=TwoWay}"/> <TextBox IsReadOnly="{Binding IsReadOnly}" Text="{Binding Zip, Mode=TwoWay}"/> Like i said this works just fine. The problem is that the Address control itself is bound to its parent object (I have several addresses I am binding). <my:AddressControl DataContext="{Binding ShippingAddress, Mode=TwoWay}" IsReadOnly="True"> <my:AddressControl DataContext="{Binding BillingAddress, Mode=TwoWay}" IsReadOnly="True"> The problem is that as soon as I set DataContext to something other than 'this' then the binding for IsReadOnly breaks. Not surprising because its looking for IsReadOnly on the Address data entity and it doesn't exist or belong there. I've tried just about every combination of binding attributes to get IsReadOnly to bind to the AddressControl obejct but can't get it working. I've tried things like this, but I can't get IsReadOnly to bind independently to the AddressControl property instead of its DataContext. <TextBox IsReadOnly="{Binding RelativeSource={RelativeSource Self}, Path=IsReadOnlyProperty}" Text="{Binding City, Mode=TwoWay}" /> I think I'm pretty close. What am I doing wrong?

    Read the article

  • How Manage Big Linq DataContext ?

    - by Rev
    Hi The major problem in .net programs is "How manage memory for best performance". so Microsoft use garbage collector in .net and with that, we don't need to do something for managing memory(or better say we can use GC easily) But when you develop big project(business app), you make too many tables and database for your own project. so if you use Linq-to-sql, we must build DataContext include hundred or more tables. That make problem for program when you create an object from datacontext, that object give big amount of memory. also we cant divide datacontext to datacontexts(cuz relation between tables) so "How manage datacontext and memory"?

    Read the article

  • How to report DataContext.SubmitChanges() progress with LINQ2SQL

    - by kzen
    If there is a foreach loop that contains DataContext.Customer.InsertOnSubmit(cust) for example: foreach (Object obj in collection) { Customer cust = new Customer { Id = obj.Id, Name = obj.Name ... }; DataContext.Customer.InsertOnSubmit(cust); } And outside of the loop there is a call to: DataContext.SubmittChanges(); Is there a way to obtain the SubmittChanges progress in order to report the progress back to the user (or a different approach without moving the SubmittChanges into the loop)?

    Read the article

  • Setting property of objects in datacontext

    - by ryudice
    Hi, all my entities have a common property which specifies the company they belong to, I would like to set this property in a method in my datacontext but I do not want to use the partial methods for each of the entity types that the datacontext provides, is there a method that receives any entity that is inserted throught the datacontext so that I can hook to it or override it and set the property using reflection? thanks.

    Read the article

  • Should I define a single "DataContext" and pass references to it around or define muliple "DataConte

    - by Nate Bross
    I have a Silverlight application that consists of a MainWindow and several classes which update and draw images on the MainWindow. I'm now expanding this to keep track of everything in a database. Without going into specifics, lets say I have a structure like this: MainWindow Drawing-Surface Class1 -- Supports Drawing DataContext + DataServiceCollection<T> w/events Class2 -- Manages "transactions" (add/delete objects from drawing) Class3 Each "Class" is passed a reference to the Drawing Surface so they can interact with it independently. I'm starting to use WCF Data Services in Class1 and its working well; however, the other classes are also going to need access to the WCF Data Services. (Should I define my "DataContext" in MainWindow and pass a reference to each child class?) Class1 will need READ access to the "transactions" data, and Class2 will need READ access to some of the drawing data. So my question is, where does it make the most sense to define my DataContext? Does it make sense to: Define a "global" WCF Data Service "Context" object and pass references to that in all of my subsequent classes? Define an instance of the "Context" for each Class1, Class2, etc Have each method that requires access to data define its own instance of the "Context" and use closures handle the async load/complete events? Would a structure like this make more sense? Is there any danger in keeping an active "DataContext" open for an extended period of time? Typical usecase of this application could range from 1 minute to 40+ minutes. MainWindow Drawing-Surface DataContext Class1 -- Supports Drawing DataServiceCollection<DrawingType> w/events Class2 -- Manages "transactions" (add/delete objects from drawing) DataServiceCollection<TransactionType> w/events Class3 DataServiceCollection<T> w/events

    Read the article

  • Multiple queries using same datacontext throws SqlException

    - by Raj
    I've search control with which I'm trying to implement search as user types something. I'm using Linq to SQL to fire queries against the database. Though it works fine usually, when user types the queries really fast some random SqlException is thrown. These are the two different error message I stumbled across recently: A severe error occurred on the current command. The results, if any, should be discarded. Invalid attempt to call Read when reader is closed. Edit: Included code DataContextFactory class: public DataContextFactory(IConnectionStringFactory connectionStringFactory) { this.dataContext = new RegionDataContext(connectionStringFactory.ConnectionString); } public DataContext Context { get { return this.dataContext; } } public void SaveAll() { this.dataContext.SubmitChanges(); } Registering IDataContextFactory with Unity // Get connection string from Application.Current settings ConnectionInfo connectionInfo = Application.Current.Properties["ConnectionInfo"] as ConnectionInfo; // Register ConnectionStringFactory with Unity container as a Singleton this.container.RegisterType<IConnectionStringFactory, ConnectionStringFactory>(new ContainerControlledLifetimeManager(), new InjectionConstructor(connectionInfo.ConnectionString)); // Register DataContextFactory with Unity container this.container.RegisterType<IDataContextFactory, DataContextFactory>(); Connection string: Data Source=.\SQLEXPRESS2008;User Instance=true;Integrated Security=true;AttachDbFilename=C:\client.mdf;MultipleActiveResultSets=true; Using datacontext from a repository class: // IDataContextFactory dependency is injected by Unity public CompanyRepository(IDataContextFactory dataContextFactory) { this.dataContextFactory = dataContextFactory; } // return List<T> of companies var results = this.dataContextFactory.Context.GetTable<CompanyEntity>() .Join(this.dataContextFactory.Context.GetTable<RegionEntity>(), c => c.regioncode, r => r.regioncode, (c, r) => new { c = c, r = r }) .Where(t => t.c.summary_region != null) .Select(t => new { Id = t.c.compcode, Company = t.c.compname, Region = t.r.regionname }).ToList(); What is the work around?

    Read the article

  • Understanding ItemsSource and DataContext in a DataGrid

    - by Ben McCormack
    I'm trying to understand how the ItemsSource and DataContext properties work in a Silverlight Toolkit DataGrid. I'm currently working with dummy data and trying to get the data in the DataGrid to update when the value of a combo box changes. My MainPage.xaml.vb file currently looks like this: Partial Public Class MainPage Inherits UserControl Private IssueSummaryList As List(Of IssueSummary) Public Sub New() GetDummyIssueSummary("Day") InitializeComponent() dgIssueSummary.ItemsSource = IssueSummaryList 'dgIssueSummary.DataContext = IssueSummaryList ' End Sub Private Sub GetDummyIssueSummary(ByVal timeInterval As String) Dim lst As New List(Of IssueSummary)() 'Generate dummy data for lst ' IssueSummaryList = lst End Sub Private Sub ComboBox_SelectionChanged(ByVal sender As System.Object, ByVal e As System.Windows.Controls.SelectionChangedEventArgs) Dim cboBox As ComboBox = CType(sender, ComboBox) Dim cboBoxItem As ComboBoxItem = CType(cboBox.SelectedValue, ComboBoxItem) GetDummyIssueSummary(cboBoxItem.Content.ToString()) End Sub End Class My XAML currently looks this for the DataGrid: <sdk:DataGrid x:Name="dgIssueSummary" AutoGenerateColumns="False" > <sdk:DataGrid.Columns> <sdk:DataGridTextColumn Binding="{Binding ProblemType}" Header="Problem Type"/> <sdk:DataGridTextColumn Binding="{Binding Count}" Header="Count"/> </sdk:DataGrid.Columns> </sdk:DataGrid> The problem is that if I set the value of the ItemsSource property of the data grid equal to IssueSummaryList, it will display the data when it loads, but it won't update when the underlying IssueSummaryList collection changes. If I set the DataContext of the grid to be IssueSummaryList, no data will be displayed when it renders. I must not understand how ItemsSource and DataContext are supposed to function, because I expect one of those properties to "just work" when I assign a List object to them. What do I need to understand and change in my code so that as data changes in the List, the data in the grid is updated?

    Read the article

  • ASP MVC C#: LINQ Foreign Key Constraint conflicts

    - by wh0emPah
    I'm having a problem with LINQ. I have 2 tables (Parent-child relation) Table1: Events (EventID, Description) Table2: Groups (GroupID, EventID(FK), Description) Now i want to create an Event an and a child. Event e = new Event(); e.Description = "test"; Datacontext.Events.InsertOnSubmit(event) Group g = new Group(); g.Description = "test2"; g.EventID = e.EventID; Datacontext.Groups.InsertOnSubmit(g); Datacontext.SubmitChanges(); When i debug, i can see that after inserting the event. the EventID has gotten a new value (auto increment). But when Datacontext.SubmitChanges(); gets called. I get the following exception "The INSERT statement conflicted with the FOREIGN KEY constraint ... I know this can be solved by creating a relation in the LINQ diagram between Events and groups. And then setting the entity itself. But i don't want to load the events everytime i ask a list of groups. All i need is some way that when inserting the group fails, the event insert won't be comitted in the database. Sorry if this is a bit unclear, My english isn't really good. Thanks in advance!

    Read the article

  • refactor LINQ TO SQL custom properties that instantiate datacontext

    - by Thiago Silva
    I am working on an existing ASP.NET MVC app that started small and has grown with time to require a good re-architecture and refactoring. One thing that I am struggling with is that we've got partial classes of the L2S entities so we could add some extra properties, but these props create a new data context and query the DB for a subset of data. This would be the equivalent to doing the following in SQL, which is not a very good way to write this query as oppsed to joins: SELECT tbl1.stuff, (SELECT nestedValue FROM tbl2 WHERE tbl2.Foo = tbl1.Bar), tbl1.moreStuff FROM tbl1 so in short here's what we've got in some of our partial entity classes: public partial class Ticket { public StatusUpdate LastStatusUpdate { get { //this static method call returns a new DataContext but needs to be refactored var ctx = OurDataContext.GetContext(); var su = Compiled_Query_GetLastUpdate(ctx, this.TicketId); return su; } } } We've got some functions that create a compiled query, but the issue is that we also have some DataLoadOptions defined in the DataContext, and because we instantiate a new datacontext for getting these nested property, we get an exception "Compiled Queries across DataContexts with different LoadOptions not supported" . The first DataContext is coming from a DataContextFactory that we implemented with the refactorings, but this second one is just hanging off the entity property getter. We're implementing the Repository pattern in the refactoring process, so we must stop doing stuff like the above. Does anyone know of a good way to address this issue?

    Read the article

  • Linq to sql DataContext cannot set load options after results been returned

    - by David Liddle
    I have two tables A and B with a one-to-many relationship respectively. On some pages I would like to get a list of A objects only. On other pages I would like to load A with objects in B attached. This can be handled by setting the load options DataLoadOptions options = new DataLoadOptions(); options.LoadWith<A>(a => a.B); dataContext.LoadOptions = options; The trouble occurs when I first of all view all A's with load options, then go to edit a single A (do not use load options), and after edit return to the previous page. I understand why the error is occurring but not sure how to best get round this problem. I would like the DataContext to be loaded up per request. I thought I was achieving this by using StructureMap to load up my DataContext on a per request basis. This is all part of an n-tier application where my Controllers call Services which in turn call Repositories. ForRequestedType<MyDataContext>() .CacheBy(InstanceScope.PerRequest) .TheDefault.Is.Object(new MyDataContext()); ForRequestedType<IAService>() .TheDefault.Is.OfConcreteType<AService>(); ForRequestedType<IARepository>() .TheDefault.Is.OfConcreteType<ARepository>(); Here is a brief outline of my Repository public class ARepository : IARepository { private MyDataContext db; public ARepository(MyDataContext context) { db = context; } public void SetLoadOptions(DataLoadOptions options) { db.LoadOptions = options; } public IQueryable<A> Get() { return from a in db.A select a; } So my ServiceLayer, on View All, sets the load options and then gets all A's. On editing A my ServiceLayer should spin up a new DataContext and just fetch a list of A's. When sql profiling, I can see that when I go to the Edit page it is requesting A with B objects.

    Read the article

  • Linq to sql add/update in different methods with different datacontexts

    - by Kurresmack
    I have to methods, Add() and Update() which both create a datacontext and returns the object created/updated. In my unit test I call first Add(), do some stuff and then call Update(). The problem is that Update() fails with the exception: System.Data.Linq.DuplicateKeyException: Cannot add an entity with a key that is already in use.. I understand the issue but want to know what to do about it? I've read a bit about how to handle multiple datacontext objects and from what I've heard this way is OK. I understand that the entity is still attached to the datacontext in Add() but I need to find out how to solve this? Thanks in advance

    Read the article

  • Setting TreeView.DataContext doesn't refresh the tree

    - by dan gibson
    I have a List that I've bound to a TreeView. Setting TreeView.DataContext works - everything displays correctly. I then change the list (add an item to it) and set TreeView.DataContext again (to the same value) but the tree does not refresh with the new items. How do I get the treeview to refresh? This is basically my code: public class xItemCollection : ObservableCollection<xItem> { } public class xItem : INotifyPropertyChanged { xItemCollection _Items; public xItem() { _Items = new xItemCollection(); } public xItemCollection Items {get{return _Items;}} } ... this.RootItem = new xItem(); treeView.DataContext = this; Adding items to the list works until the tree is rendered for the first time. After it is rendered, adding/removing items does not refresh the tree.

    Read the article

  • ASP.NET Thread Safety in aspx.cs code behind file

    - by Tim Michalski
    I am thinking of adding a DataContext as a member variable to my aspx.cs code-behind class for executing LinqToSql queries. Is this thread safe? I am not sure if a new instance of this code-behind class is created for each HTTP request, or if the instance is shared amongst all request threads? My fear is that I will get 10 simultaneous concurrent http requests that will be using the same database session. public partial class MyPage : System.Web.UI.Page { private DataContext myDB = new DataContext(); protected void MyAction_Click(object sender, EventArgs e) { myDB.DoWork(); } }

    Read the article

  • Joins in LINQ to SQL

    - by rajbk
    The following post shows how to write different types of joins in LINQ to SQL. I am using the Northwind database and LINQ to SQL for these examples. NorthwindDataContext dataContext = new NorthwindDataContext(); Inner Join var q1 = from c in dataContext.Customers join o in dataContext.Orders on c.CustomerID equals o.CustomerID select new { c.CustomerID, c.ContactName, o.OrderID, o.OrderDate }; SELECT [t0].[CustomerID], [t0].[ContactName], [t1].[OrderID], [t1].[OrderDate]FROM [dbo].[Customers] AS [t0]INNER JOIN [dbo].[Orders] AS [t1] ON [t0].[CustomerID] = [t1].[CustomerID] Left Join var q2 = from c in dataContext.Customers join o in dataContext.Orders on c.CustomerID equals o.CustomerID into g from a in g.DefaultIfEmpty() select new { c.CustomerID, c.ContactName, a.OrderID, a.OrderDate }; SELECT [t0].[CustomerID], [t0].[ContactName], [t1].[OrderID] AS [OrderID], [t1].[OrderDate] AS [OrderDate]FROM [dbo].[Customers] AS [t0]LEFT OUTER JOIN [dbo].[Orders] AS [t1] ON [t0].[CustomerID] = [t1].[CustomerID] Inner Join on multiple //We mark our anonymous type properties as a and b otherwise//we get the compiler error "Type inferencce failed in the call to 'Join’var q3 = from c in dataContext.Customers join o in dataContext.Orders on new { a = c.CustomerID, b = c.Country } equals new { a = o.CustomerID, b = "USA" } select new { c.CustomerID, c.ContactName, o.OrderID, o.OrderDate }; SELECT [t0].[CustomerID], [t0].[ContactName], [t1].[OrderID], [t1].[OrderDate]FROM [dbo].[Customers] AS [t0]INNER JOIN [dbo].[Orders] AS [t1] ON ([t0].[CustomerID] = [t1].[CustomerID]) AND ([t0].[Country] = @p0) Inner Join on multiple with ‘OR’ clause var q4 = from c in dataContext.Customers from o in dataContext.Orders.Where(a => a.CustomerID == c.CustomerID || c.Country == "USA") select new { c.CustomerID, c.ContactName, o.OrderID, o.OrderDate }; SELECT [t0].[CustomerID], [t0].[ContactName], [t1].[OrderID], [t1].[OrderDate]FROM [dbo].[Customers] AS [t0], [dbo].[Orders] AS [t1]WHERE ([t1].[CustomerID] = [t0].[CustomerID]) OR ([t0].[Country] = @p0) Left Join on multiple with ‘OR’ clause var q5 = from c in dataContext.Customers from o in dataContext.Orders.Where(a => a.CustomerID == c.CustomerID || c.Country == "USA").DefaultIfEmpty() select new { c.CustomerID, c.ContactName, o.OrderID, o.OrderDate }; SELECT [t0].[CustomerID], [t0].[ContactName], [t1].[OrderID] AS [OrderID], [t1].[OrderDate] AS [OrderDate]FROM [dbo].[Customers] AS [t0]LEFT OUTER JOIN [dbo].[Orders] AS [t1] ON ([t1].[CustomerID] = [t0].[CustomerID]) OR ([t0].[Country] = @p0)

    Read the article

  • WPF MVVM Pattern, ViewModel DataContext question

    - by orangecl4now
    I used this side to create my demo application http://windowsclient.net/learn/video.aspx?v=314683 The site was very useful in getting my started and in their example, they created a file called EmployeeRepository.cs which appears to be the source for the data. In their example, the data was hard-wired in code. So I'm trying to learn how to get the data from a data source (like a DB). In my specific case, I want to get the data from a Microsoft Access DB. (READ ONLY, So I'll only use SELECT commands). using System.Collections.Generic; using Telephone_Directory_2010.Model; namespace Telephone_Directory_2010.DataAccess { public class EmployeeRepository { readonly List<Employee> _employees; public EmployeeRepository() { if (_employees == null) { _employees = new List<Employee>(); } _employees.Add(Employee.CreateEmployee("Student One", "IT201", "Information Technology", "IT4207", "Building1", "Room650")); _employees.Add(Employee.CreateEmployee("Student Two", "IT201", "Information Technology", "IT4207", "Building1", "Room650")); _employees.Add(Employee.CreateEmployee("Student Three", "IT201", "Information Technology", "IT4207", "Building1", "Room650")); } public List<Employee> GetEmployees() { return new List<Employee>(_employees); } } } I found another example where an Access DB is used but it doesn't comply with MVVM. So I was trying to figure out how to add the DB file to the project, how to wire it up and bind it to a listbox (i'm not that far yet). Below is my modified file using System.Collections.Generic; using Telephone_Directory_2010.Model; // integrating new code with working code using Telephone_Directory_2010.telephone2010DataSetTableAdapters; using System.Windows.Data; namespace Telephone_Directory_2010.DataAccess { public class EmployeeRepository { readonly List<Employee> _employees; // start // integrating new code with working code private telephone2010DataSet.telephone2010DataTable employeeTable; private CollectionView dataView; internal CollectionView DataView { get { if (dataView == null) { dataView = (CollectionView) CollectionViewSource.GetDefaultView(this.DataContext); } return dataView; } } public EmployeeRepository() { if (_employees == null) { _employees = new List<Employee>(); } telephone2010TableAdapter employeeTableAdapter = new telephone2010TableAdapter(); employeeTable = employeeTableAdapter.GetData(); this.DataContext = employeeTable; } public List<Employee> GetEmployees() { return new List<Employee>(_employees); } } } I get the following error messages when building Error 1 'Telephone_Directory_2010.DataAccess.EmployeeRepository' does not contain a definition for 'DataContext' and no extension method 'DataContext' accepting a first argument of type 'Telephone_Directory_2010.DataAccess.EmployeeRepository' could be found (are you missing a using directive or an assembly reference?) C:\Projects\VS2010\Telephone Directory 2010\Telephone Directory 2010\DataAccess\EmployeeRepository.cs 23 90 Telephone Directory 2010

    Read the article

  • How Can I fetch the Data from DATAContext

    - by SHASHANK
    hello all i have a problem, i have some data in Datacontext and i want to fetch this data how can i achive it thanks in advance shashank button1.DataContext = new DataView(tablename, "field1 in (" + stringbuilder.ToString() + "0)", "field1", DataViewRowState.CurrentRows);

    Read the article

  • LINQ 2 SQL: Partial Classes

    - by Refracted Paladin
    I need to set the ConnectionString for my DataContext's based on an AppSetting. I am trying to do this by creating a Partial Class for each DataContext. The below is what I have so far and I am wondering if I am overlooking something? Specifically, am I dealing with my DataContext's correctly(disposing, staleness, etc)? Doing it this way will I have issues with Updates and Inserts? Is the file BLLAspnetdb.cs useful or neccessary in the least or should all of that be in the generated partial class AspnetdbDataContext file? In short, is this an acceptable structure or will this cause me issues as I elaborate it? dbml File Name = Aspnetdb.dbml Partial Class File Name = Aspnetdb.cs partial class AspnetdbDataContext { public static bool IsDisconnectedUser { get { return Convert.ToBoolean(ConfigurationManager.AppSettings["IsDisconnectedUser"]) == true; } } public static AspnetdbDataContext New { get { var cs = IsDisconnectedUser ? Settings.Default.Central_aspnetdbConnectionString : Settings.Default.aspnetdbConnectionString; return new AspnetdbDataContext(cs); } } } My Created File Name = BLLAspnetdb.cs public class BLLAspnetdb { public static IList WorkerList(Guid userID) { var DB = AspnetdbDataContext.New; var workers = from user in DB.tblDemographics where user.UserID == userID select new { user.FirstName, user.LastName, user.Phone }; IList theWorkers = workers.ToList(); return theWorkers; } public static String NurseName(Guid? userID) { var DB = AspnetdbDataContext.New; var nurseName = from demographic in DB.tblDemographics where demographic.UserID == userID select demographic.FirstName +" " + demographic.LastName; return nurseName.SingleOrDefault(); } public static String SocialWorkerName(Guid? userID) { var DB = AspnetdbDataContext.New; var swName = from demographic in DB.tblDemographics where demographic.UserID == userID select demographic.FirstName + " " + demographic.LastName; return swName.SingleOrDefault(); } } see this previous question and the accepted answer for background on how I got to here... switch-connectionstrings-between-local-and-remote-with-linq-to-sql

    Read the article

  • Access property of DataContext in ItemTemplate

    - by amrinder
    My datacontext has two properties: Items which is a collection and DetailsVisiblity which is enum of type Visiblity. On the page I have a Listbox with ItemsSource="{Binding Entries}". Inside the DataTemplate, I can bind stuff to properties of Items, but how do I get access to DetailsVisiblity which is a property of DataContext? DataContext has two properties: ObservableCollection<Item> Entries, and Visibility DetailsVisiblity. Item class has two properties: Title and Details. Here is the view. How do I bind Visiblity of the second TextBlock to DetailsVisiblity property? <ListBox "{Binding Items}"> <ListBox.ItemTemplate> <DataTemplate> <StackPanel> <TextBlock Text="{Binding Title}" /> <TextBlock Text="{Binding Details}" Visibility="{Binding ???}" /> </StackPanel> </DataTemplate> </ListBox.ItemTemplate> </ListBox>

    Read the article

  • Can't delete record via the datacontext it was retrieved from

    - by Antilogic
    I just upgraded one of my application's methods to use compiled queries (not sure if this is relevant). Now I'm getting contradicting error messages when I run the code. This is my method: MyClass existing = Queries.MyStaticCompiledQuery(MyRequestScopedDataContext, param1, param2).SingleOrDefault(); if (existing != null) { MyRequestScopedDataContext.MyClasses.DeleteOnSubmit(existing); } When I run it I get this message: Cannot remove an entity that has not been attached. Note that the compiled query and the DeleteOnSubmit reference the same DataContext. Still I figured I'd humor the application and add an attach command before the DeleteOnSubmit, like so: MyClass existing = Queries.MyStaticCompiledQuery(MyRequestScopedDataContext, param1, param2).SingleOrDefault(); if (existing != null) { MyRequestScopedDataContext.MyClasses.Attach(existing); MyRequestScopedDataContext.MyClasses.DeleteOnSubmit(existing); } BUT... When I run this code, I get a completely different contradictory error message: An attempt has been made to Attach or Add an entity that is not new, perhaps having been loaded from another DataContext. This is not supported. I'm at a complete loss... Does anyone else have some insight as to why I can't delete a record via the same DataContext I retrieved it from?

    Read the article

  • SqlDateTime overflow on INSERT when date is correct using a Linq to SQL DataContext

    - by Jan Hoefnagels
    Dear Linq experts, I get an SqlDateTime overflow error (Must be between 1/1/1753 12:00:00 AM and 12/31/9999 11:59:59 PM.) when doing an INSERT using an Linq DataContext connected to SQL Server database when I do the SubmitChanges(). When I use the debugger the date value is correct. Even if I temporary update the code to set the date value to DateTime.Now it will not do the insert. Did anybody found a work-around for this behaviour? Maybe there is a way to check what SQL the datacontext submits to the database.

    Read the article

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