Search Results

Search found 436 results on 18 pages for 'iqueryable'.

Page 16/18 | < Previous Page | 12 13 14 15 16 17 18  | Next Page >

  • Delaying LINQ to SQL Select Query Execution

    - by Maxim Z.
    I'm building an ASP.NET MVC site that uses LINQ to SQL. In my search method that has some required and some optional parameters, I want to build a LINQ query while testing for the existence of those optional parameters. Here's what I'm currently thinking: using(var db = new DBDataContext()) { IQueryable<Listing> query = null; //Handle required parameter query = db.Listings.Where(l => l.Lat >= form.bounds.extent1.latitude && l.Lat <= form.bounds.extent2.latitude); //Handle optional parameter if (numStars != null) query = query.Where(l => l.Stars == (int)numStars); //Other parameters... //Execute query (does this happen here?) var result = query.ToList(); //Process query... Will this implementation "bundle" the where clauses and then execute the bundled query? If not, how should I implement this feature? Also, is there anything else that I can improve? Thanks in advance.

    Read the article

  • Applying correct bindings to WPF datatemplate to maximize reusability

    - by johncatfish
    Hi. I have a WPF application. I want to apply that datatemplate to a Listbox filled with records from Table02. Then, for each listboxitem I need to bind the combobox to the same database table (Table01), but for each listboxitem the selected item will vary. It will be a foreign key to Table01. <DataTemplate x:Key="Table01DataTemplate"> <Grid> <ComboBox ItemsSource="{Binding Model.IQueryable_Table01, RelativeSource={RelativeSource FindAncestor, AncestorType={x:Type Window}}}" SelectedValue="{Binding Table01_ForeignKey}" DisplayMemberPath="name" SelectedValuePath="id" /> <!-- Other stuff --> </Grid> </DataTemplate> <ListBox x:Name="lbTest" ItemTemplate="{StaticResource Table01DataTemplate}" /> <!-- In .cs file lbTest.DataContext = this; --> Notes: Model.IQueryable_Table01 is a property which encapsulates a Linq-to-sql call returning a IQueryable. lbTest will be filled by setting ItemsSource with a Linq-to-sql call. Is this a good way to do the bindings in a data template for a maximum reusability? I also thought of replacing AncestorType={x:Type Window} with lbTest.DataContext = this; AncestorType={x:Type Application} and lbTest.DataContext = App.Current; But it didn't work (Exception on loading) and I don't know if there's any caveats or down-sides to this approach. Is this good? Any suggestions or improvements? Thanks.

    Read the article

  • performing more than one Where in query return null!!! why? how to fix this?

    - by Sadegh
    hi, i have wrote a method that filters output with provided query and return it. when one Where excuted; it return correct output but when more than one Where excuted; output is null and Exception occured with message "Enumeration yielded no results". why? how i can fix it? public IQueryable<SearchResult> PerformSearch(string query, int skip = 0, int take = 5) { if (!string.IsNullOrEmpty(query)) { var queryList = query.Split('+').ToList(); var results = GENERATERESULTS(); string key; foreach (string _q in queryList) { if (_q.StartsWith("(") && _q.EndsWith(")")) { key = _q.Replace("(", "").Replace(")", ""); results = results.Where(q => q.Title.Contains(key, StringComparison.CurrentCultureIgnoreCase)); } else if (_q.StartsWith("\"") && _q.EndsWith("\"")) { key = _q.Replace("\"", "").Replace("\"", ""); results = results.Where(q => q.Title.Contains(key, StringComparison.CurrentCulture)); } else if (_q.StartsWith("-(") && _q.EndsWith(")")) { key = _q.Replace("-(", "").Replace(")", ""); results = results.Where(q=> !q.Title.Contains(key, StringComparison.CurrentCultureIgnoreCase)); } else { key = _q; results = results.Where(q => q.Title.Contains(key, StringComparison.CurrentCulture)); } } this._Count = results.Count(); results = results.Skip(skip).Take(take); this._EndOn = DateTime.Now; this.ExecutionTime(); return results; } else return null; } thanks in advance ;)

    Read the article

  • EFv1 mapping 1 to many Relationship to POCOs

    - by Scott
    I'm trying to work through a problem where I'm mapping EF Entities to POCO which serve as DTO. I have two tables within my database, say Products and Categories. A Product belongs to one category and one category may contain many Products. My EF entities are named efProduct and efCategory. Within each entity there is the proper Navigation Property between efProduct and efCategory. My Poco objects are simple public class Product { public string Name { get; set; } public int ID { get; set; } public double Price { get; set; } public Category ProductType { get; set; } } public class Category { public int ID { get; set; } public string Name { get; set; } public List<Product> products { get; set; } } To get a list of products I am able to do something like public IQueryable<Product> GetProducts() { return from p in ctx.Products select new Product { ID = p.ID, Name = p.Name, Price = p.Price ProductType = p.Category }; } However there is a type mismatch error because p.Category is of type efCategory. How can I resolve this? That is, how can I convert p.Category to type Category? I know in .NET EF has added support for POCO, but I'm forced to use .NET 3.5 SP1.

    Read the article

  • EF4 + STE: Reattaching via a WCF Service? Using a new objectcontext each and every time?

    - by Martin
    Hi there, I am planning to use WCF (not ria) in conjunction with Entity Framework 4 and STE (Self tracking entitites). If i understnad this correctly my WCF should return an entity or collection of entities (using LIST for example and not IQueryable) to the client (in my case silverlight) The client then can change the entity or update it. At this point i believe it is self tracking???? This is where i sort of get a bit confused as there are a lot of reported problems with STEs not tracking.. Anyway... Then to update i just need to send back the entity to my WCF service on another method to do the update. I should be creating a new OBJECTCONTEXT everytime? In every method? If i am creaitng a new objectcontext everytime in everymethod on my WCF then don't i need to re-attach the STE to the objectcontext? So basically this alone wouldn't work?? using(var ctx = new MyContext()) { ctx.Orders.ApplyChanges(order); ctx.SaveChanges(); } Or should i be creating the object context once in the constructor of the WCF service so that 1 call and every additional call using the same wcf instance uses the same objectcontext? I could create and destroy the wcf service in each method call from the client - hence creating in effect a new objectcontext each time. I understand that it isn't a good idea to keep the objectcontext alive for very long. Any insight or information would be gratefully appreciated thanks

    Read the article

  • ASP.Net MVC - how can I easily serialize query results to a database?

    - by Mortanis
    I've been working on a little property search engine while I learn ASP.Net MVC. I've gotten the results from various property database tables and sorted them into a master generic property response. The search form is passed via Model Binding and works great. Now, I'd like to add pagination. I'm returning the chunk of properties for the current page with .Skip() and .Take(), and that's working great. I have a SearchResults model that has the paged result set and various other data like nextPage and prevPage. Except, I no longer have the original form of course to pass to /Results/2. Previously I'd have just hidden a copy of the form and done a POST each time, but it seems inelegant. I'd like to serialize the results to my MS SQL database and return a unique key for that results set - this also helps with a "Send this query to a friend!" link. Killing two birds with one stone. Is there an easy way to take an IQueryable result set that I have, serialize it, stick it into the DB, return a unique key and then reverse the process with said key? I'm using Linq to SQL currently on a MS SQL Express install, though in production it'll be on MS SQL 2008.

    Read the article

  • What does this model error says in asp.net mvc?

    - by Pandiya Chendur
    My Html action link takes me to a view where i can see the details.. For Ex:http://localhost:1985/Materials/Details/4 But it shows error, The model item passed into the dictionary is of type 'System.Data.Linq.DataQuery`1[CrMVC.Models.ConstructionRepository+Materials]' but this dictionary requires a model item of type 'CrMVC.Models.ConstructionRepository+Materials'. And my model is... public IQueryable<Materials> GetMaterial(int id) { return from m in db.Materials join Mt in db.MeasurementTypes on m.MeasurementTypeId equals Mt.Id where m.Mat_id == id select new Materials() { Id = Convert.ToInt64(m.Mat_id), Mat_Name = m.Mat_Name, Mes_Name = Mt.Name, }; } public class Materials { private Int64 id; public string mat_Name; public string mes_Name; public Int64 Id { get { return id; } set { id = value; } } public string Mat_Name { get { return mat_Name; } set { mat_Name = value; } } public string Mes_Name { get { return mes_Name; } set { mes_Name = value; } } } } and my controller method... public ActionResult Details(int id) { var material = consRepository.GetMaterial(id).AsQueryable(); return View("Details", material); } Any suggestion what am i missing here?

    Read the article

  • RIA Service/oData ... "Requests that attempt to access a single element using key values from a resu

    - by user327911
    I've recently started working up a sample project to play with an oData feed coming from a RIA service. I am able to view the feed and the metadata via any web browser, however, if I try to perform certain query operations on the feed I receive "unsupported" exceptions. Sample oData feed: ProductSet http://localhost:50880/Services/Rebirth-Web-Services-ProductService.svc/OData/ProductSet/ 2010-04-28T14:02:10Z http://localhost:50880/Services/Rebirth-Web-Services-ProductService.svc/OData/ProductSet(guid'b0a2b170-c6df-441f-ae2a-74dd19901128') 2010-04-28T14:02:10Z b0a2b170-c6df-441f-ae2a-74dd19901128 Product 0 Type 1 Active Sample web.config entry: Sample service: [EnableClientAccess()] public class ProductService : DomainService { [Query(IsDefault = true)] public IQueryable GetProducts() { IList products = new List(); for (int i = 0; i < 90; i++) { Product product = new Product { Id = Guid.NewGuid(), Name = "Product " + i.ToString(), ProductType = i < 30 ? "Type 1" : ((i > 30 && i < 60) ? "Type 2" : "Type 3"), Status = i % 2 == 0 ? "Active" : "NotActive" }; products.Add(product); } return products.AsQueryable(); } } If I provide the url "http://localhost:50880/Services/Rebirth-Web-Services-ProductService.svc/OData/ProductSet(guid'b0a2b170-c6df-441f-ae2a-74dd19901128')" to my web browser I receive the following xml: Requests that attempt to access a single element using key values from a result set are not supported. I'm new to RIA and oData. Could this be something as simple as my web browsers not supporting this type of querying on the result set or something else? Thanks ahead! Corey

    Read the article

  • Fasted way to develop data entry screens for a .NET backend ?

    - by jay23
    I am a .NET / C# back end guy. I am working on a app that will have about 200 different data entry screens. For me exposing DTO as a collection for CRUD (IUpdatable and IQueryable) is the easy part, can do it in sleep :-). What I am trying to decide is what type of front end technology will allow me to develop these data entry screens fast. They don't have to be fancy but they are not just plain grid either and on average they have about 15 form fields and some client side data validation (no db look up) Options I am looking at are Use ExtJS on the front and REST / JSON on the back. ASP.NET RIA but I do not know SL (Well XAML) Plain ASP.NET / MVC One idea I had was the DTO will contain the meta data about the form (As Attributes) and the form can be dynamically generated, but i do not want to reinvent the wheel if their is an easy way. I have looked at RAD software but all of them look at the DB and generate screens. I rather want some thing that can look at my DTO and generate screens. Jay

    Read the article

  • How can I merge two Linq IEnumerable<T> queries without running them?

    - by makerofthings7
    How do I merge a List<T> of TPL-based tasks for later execution? public async IEnumerable<Task<string>> CreateTasks(){ /* stuff*/ } My assumption is .Concat() but that doesn't seem to work: void MainTestApp() // Full sample available upon request. { List<string> nothingList = new List<string>(); nothingList.Add("whatever"); cts = new CancellationTokenSource(); delayedExecution = from str in nothingList select AccessTheWebAsync("", cts.Token); delayedExecution2 = from str in nothingList select AccessTheWebAsync("1", cts.Token); delayedExecution = delayedExecution.Concat(delayedExecution2); } /// SNIP async Task AccessTheWebAsync(string nothing, CancellationToken ct) { // return a Task } I want to make sure that this won't spawn any task or evaluate anything. In fact, I suppose I'm asking "what logically executes an IQueryable to something that returns data"? Background Since I'm doing recursion and I don't want to execute this until the correct time, what is the correct way to merge the results if called multiple times? If it matters I'm thinking of running this command to launch all the tasks var AllRunningDataTasks = results.ToList(); followed by this code: while (AllRunningDataTasks.Count > 0) { // Identify the first task that completes. Task<TableResult> firstFinishedTask = await Task.WhenAny(AllRunningDataTasks); // ***Remove the selected task from the list so that you don't // process it more than once. AllRunningDataTasks.Remove(firstFinishedTask); // TODO: Await the completed task. var taskOfTableResult = await firstFinishedTask; // Todo: (doen't work) TrustState thisState = (TrustState)firstFinishedTask.AsyncState; // TODO: Update the concurrent dictionary with data // thisState.QueryStartPoint + thisState.ThingToSearchFor Interlocked.Decrement(ref thisState.RunningDirectQueries); Interlocked.Increment(ref thisState.CompletedDirectQueries); if (thisState.RunningDirectQueries == 0) { thisState.TimeCompleted = DateTime.UtcNow; } }

    Read the article

  • Trying to edit an entity with data from dropdowns in MVC...

    - by user598352
    Hello! I'm having trouble getting my head around sending multiple models to a view in mvc. My problem is the following. Using EF4 I have a table with attributes organised by category. Couldn't post an image :-( [Have a table called attributes (AttributeTitle, AttributeName, CategoryID) connected to a table called Category (CategoryTitle).] What I want to do is be able to edit an attribute entity and have a dropdown of categories to choose from. I tried to make a custom viewmodel public class AttributeViewModel { public AttributeViewModel() { } public Attribute Attribute { get; set; } public IQueryable<Category> AllCategories { get; set; } } But it just ended up being a mess. <div class="editor-field"> <%: Html.DropDownList("Category", new SelectList((IEnumerable)Model.AllCategories, "CategoryID", "CategoryName")) %> </div> I was getting it back to the controller... [HttpPost] public ActionResult Edit(int AttributeID, FormCollection formcollection) { var _attribute = ProfileDB.GetAttribute(AttributeID); int _selcategory = Convert.ToInt32(formcollection["Category"]); _attribute.CategoryID = (int)_selcategory; try { UpdateModel(_attribute); (<---Error here) ProfileDB.SaveChanges(); return RedirectToAction("Index"); } catch (Exception e) { return View(_attribute); } } I've debugged the code and my _attribute looks correct and _attribute.CategoryID = (int)_selcategory updates the model, but then I get the error. Somewhere here I thought that there should be a cleaner way to do this, and that if I could only send two models to the view instead of having to make a custom viewmodel. To sum it up: I want to edit my attribute and have a dropdown of all of the available categories. Any help much appreciated!

    Read the article

  • Cannot perform an ORDERBY against my EF4 data

    - by Jaxidian
    I have a query hitting EF4 using STEs and I'm having an issue with user-defined sorting. In debugging this, I have removed the dynamic sorting and am hard-coding it and I still have the issue. If I swap/uncomment the var results = xxx lines in GetMyBusinesses(), my results are not sorted any differently - they are always sorting it ascendingly. FYI, Name is a varchar(200) field in SQL 2008 on my Business table. private IQueryable<Business> GetMyBusinesses(MyDBContext CurrentContext) { var myBusinesses = from a in CurrentContext.A join f in CurrentContext.F on a.FID equals f.id join b in CurrentContext.Businesses on f.BID equals b.id where a.PersonID == 52 select b; var results = from r in myBusinesses orderby "Name" ascending select r; //var results = from r in results // orderby "Name" descending // select r; return results; } private PartialEntitiesList<Business> DoStuff() { var myBusinesses = GetMyBusinesses(); var myBusinessesCount = GetMyBusinesses().Count(); Results = new PartialEntitiesList<Business>(myBusinesses.Skip((PageNumber - 1)*PageSize).Take(PageSize).ToList()) {UnpartialTotalCount = myBusinessesCount}; return Results; } public class PartialEntitiesList<T> : List<T> { public PartialEntitiesList() { } public PartialEntitiesList(int capacity) : base(capacity) { } public PartialEntitiesList(IEnumerable<T> collection) : base(collection) { } public int UnpartialTotalCount { get; set; } }

    Read the article

  • RIA Service - without database?

    - by Heko
    Helo! I need to write a RIA service to call Java webservices from Silverlight 3.0 app. I'm testing how stuff works and in my Web app I have a MyData class which has 2 properties (int ID, string Text): namespace SilverlightApplication1.Web { public class MyData { [Key] public int ID { get; set; } public string Text { get; set; } } } Then I wrote simple DomainService: [EnableClientAccess()] public class MyService : DomainService { public IQueryable<MyData> GetMyData(string Url) { // here I will call my WebService List<MyData> result = new List<MyData>(); result.Add(new MyData { ID = 1, Text = Url }); return result.AsQueryable(); } } } How can I get data into my SL app? Now I have this: namespace SilverlightApplication1 { public partial class MainPage : UserControl { public MainPage() { InitializeComponent(); MyContext context = new MyContext(); } } } I called and load but nothink worsk (exceptions, or nulls)... I had Invoke annotation but MyData is not TEntity and I can't use Strings or other simple types as well... :/ I'm reading and reading posts and nothing works like it should.. Any help would be really appreciated. Thank you!

    Read the article

  • Paging using Linq-To-Sql based on two parameters in asp.net mvc...

    - by Pandiya Chendur
    As two parameters i say currentPage and pagesize .....I thus far used sql server stored procedures and implemented paging like this, GO ALTER PROCEDURE [dbo].[GetMaterialsInView] -- Add the parameters for the stored procedure here @CurrentPage INT, @PageSize INT AS BEGIN -- SET NOCOUNT ON added to prevent extra result sets from -- interfering with SELECT statements. SET NOCOUNT ON; SELECT *,ROW_NUMBER() OVER (ORDER BY Id) AS Row FROM ( SELECT *,ROW_NUMBER() OVER (ORDER BY Id) AS Row FROM InTimePagingView ) AS InTimePages WHERE Row >= (@CurrentPage - 1) * @PageSize + 1 AND Row <= @CurrentPage*@PageSize SELECT COUNT(*) as TotalCount FROM InTimePagingView SELECT CEILING(COUNT(*) / CAST(@PageSize AS FLOAT)) NumberOfPages FROM InTimePagingView END Now i am using Linq-to-sql and i use this, public IQueryable<MaterialsObj> FindAllMaterials() { var materials = from m in db.Materials join Mt in db.MeasurementTypes on m.MeasurementTypeId equals Mt.Id where m.Is_Deleted == 0 select new MaterialsObj() { Id = Convert.ToInt64(m.Mat_id), Mat_Name = m.Mat_Name, Mes_Name = Mt.Name, }; return materials; } Now i want to return the records,TotalCount where i use Total count to generate pagenumbers..... Is this possible... Any suggestion... EDIT: Just found this... NorthWindDataContext db = new NorthWindDataContext(); var query = from c in db.Customers select c.CompanyName; //Assuming Page Number = 2, Page Size = 10 int iPageNum = 2; int iPageSize = 10; var PagedData = query.Skip((iPageNum - 1) * iPageSize).Take(iPageSize); ObjectDumper.Write(PagedData);

    Read the article

  • Project Naming Convention Feedback Please

    - by Sam Striano
    I am creating a ASP.NET MVC 3 application using Entity Framework 4. I am using the Repository/Service Pattern and was looking for feedback. I currently have the following: MVC Application (GTG.dll) GTG GTG.Controllers GTG.ViewModels Business POCO's (GTG.Business.dll) This contains all business objects (Customer, Order, Invoice, etc...) EF Model/Repositories (GTG.Data.dll) GTG.Business (GTG.Context.tt) I used the Entity POCO Generator Templates. GTG.Data.Repositories Service Layer (GTG.Data.Services.dll) GTG.Data.Services - Contains all of the service objects, one per aggregate root. The following is a little sample code: Controller Namespace Controllers Public Class HomeController Inherits System.Web.Mvc.Controller Function Index() As ActionResult Return View(New Models.HomeViewModel) End Function End Class End Namespace Model Namespace Models Public Class HomeViewModel Private _Service As CustomerService Public Property Customers As List(Of Customer) Public Sub New() _Service = New CustomerService _Customers = _Service.GetCustomersByBusinessName("Striano") End Sub End Class End Namespace Service Public Class CustomerService Private _Repository As ICustomerRepository Public Sub New() _Repository = New CustomerRepository End Sub Function GetCustomerByID(ByVal ID As Integer) As Customer Return _Repository.GetByID(ID) End Function Function GetCustomersByBusinessName(ByVal Name As String) As List(Of Customer) Return _Repository.Query(Function(x) x.CompanyName.StartsWith(Name)).ToList End Function End Class Repository Namespace Data.Repositories Public Class CustomerRepository Implements ICustomerRepository Public Sub Add(ByVal Entity As Business.Customer) Implements IRepository(Of Business.Customer).Add End Sub Public Sub Delete(ByVal Entity As Business.Customer) Implements IRepository(Of Business.Customer).Delete End Sub Public Function GetByID(ByVal ID As Integer) As Business.Customer Implements IRepository(Of Business.Customer).GetByID Using db As New GTGContainer Return db.Customers.FirstOrDefault(Function(x) x.ID = ID) End Using End Function Public Function Query(ByVal Predicate As System.Linq.Expressions.Expression(Of System.Func(Of Business.Customer, Boolean))) As System.Linq.IQueryable(Of Business.Customer) Implements IRepository(Of Business.Customer).Query Using db As New GTGContainer Return db.Customers.Where(Predicate) End Using End Function Public Sub Save(ByVal Entity As Business.Customer) Implements IRepository(Of Business.Customer).Save End Sub End Class End Namespace

    Read the article

  • Mongodb, linq driver. How to construct Contains with variable or statements

    - by Syska
    I'm using the LINQ Driver for C#, works great. Sorting a lot of properties but heres a problem I can't solve, its probebly simple. var identifierList = new []{"10", "20", "30"}; var newList = list.Where(x => identifierList.Contains(x.Identifier)); This is NOT supported ... So I could do something like: var newList = list.Where(x => x.Identifier == "10" || x.Identifier == "20" || x.Identifier == "30"); But since the list is variable ... how do I construct the above? Or are there even better alternatives? The list is of type IQueryable<MyCustomClass> For information ... this is used as a filter of alot of properties. In SQL I could have a parent - child relationship. But as I can't as the parent for the main ID I need to take all the ID's out and then construct it like this. Hopes this makes sense. If needed I will explain more.

    Read the article

  • LINQ - 'Could not translate expression' with previously used and proven query condition

    - by tomfumb
    I am fairly new to LINQ and can't get my head around some inconsistency in behaviour. Any knowledgeable input would be much appreciated. I see similar issues on SO and elsewhere but they don't seem to help. I have a very simple setup - a company table and an addresses table. Each company can have 0 or more addresses, and if 0 one must be specified as the main address. I'm trying to handle the cases where there are 0 addresses, using an outer join and altering the select statement accordingly. Please note I'm currently binding the output straight to a GridView so I would like to keep all processing within the query. The following DOES work IQueryable query = from comp in context.Companies join addr in context.Addresses on comp.CompanyID equals addr.CompanyID into outer // outer join companies to addresses table to include companies with no address from addr in outer.DefaultIfEmpty() where (addr.IsMain == null ? true : addr.IsMain) == true // if a company has no address ensure it is not ruled out by the IsMain condition - default to true if null select new { comp.CompanyID, comp.Name, AddressID = (addr.AddressID == null ? -1 : addr.AddressID), // use -1 to represent a company that has no addresses MainAddress = String.Format("{0}, {1}, {2} {3} ({4})", addr.Address1, addr.City, addr.Region, addr.PostalCode, addr.Country) }; but this displays an empty address in the GridView as ", , ()" So I updated the MainAddress field to be MainAddress = (addr.AddressID == null ? "" : String.Format("{0}, {1}, {2} {3} ({4})", addr.Address1, addr.City, addr.Region, addr.PostalCode, addr.Country)) and now I'm getting the Could not translate expression error and a bunch of spewey auto-generated code in the error which means very little to me. The condition I added to MainAddress is no different to the working condition on AddressID, so can anybody tell me what's going on here? Any help greatly appreciated.

    Read the article

  • Is there such a thing as a MemberExpression that handles a many-to-many relationship?

    - by Jaxidian
    We're trying to make it easy to write strongly-typed code in all areas of our system, so rather than setting var sortColumn = "FirstName" we'd like to say sortOption = (p => p.FirstName). This works great if the sortOption is of type Expression<Func<Person, object>> (we actually use generics in our code but that doesn't matter). However, we run into problems for many-to-many relationships because this notation breaks down. Consider this simple code: internal class Business { public IQueryable<Address> Addresses { get; set; } public string Name { get; set; } } internal class Address { public State MyState { get; set; } } internal class State { public string Abbreviation { get; set; } public int StateID { get; set; } } Is it possible to have this sort of MemberExpression to identify the StateID column off of a business? Again, the purpose of using this is not to return a StateID object, it's to just identify that property off of that entity (for sorting, filtering, and other purposes). It SEEMS to me that there should be some way to do this, even if it's not quite as pretty as foo = business.Addresses.SomeExtension(a => a.State.StateID);. Is this really possible? If more background is needed, take a look at this old question of mine. We've since updated the code significantly, but this should give you the general detailed idea of the context behind this question.

    Read the article

  • Entity Framework Batch Update and Future Queries

    - by pwelter34
    Entity Framework Extended Library A library the extends the functionality of Entity Framework. Features Batch Update and Delete Future Queries Audit Log Project Package and Source NuGet Package PM> Install-Package EntityFramework.Extended NuGet: http://nuget.org/List/Packages/EntityFramework.Extended Source: http://github.com/loresoft/EntityFramework.Extended Batch Update and Delete A current limitations of the Entity Framework is that in order to update or delete an entity you have to first retrieve it into memory. Now in most scenarios this is just fine. There are however some senerios where performance would suffer. Also, for single deletes, the object must be retrieved before it can be deleted requiring two calls to the database. Batch update and delete eliminates the need to retrieve and load an entity before modifying it. Deleting //delete all users where FirstName matches context.Users.Delete(u => u.FirstName == "firstname"); Update //update all tasks with status of 1 to status of 2 context.Tasks.Update( t => t.StatusId == 1, t => new Task {StatusId = 2}); //example of using an IQueryable as the filter for the update var users = context.Users .Where(u => u.FirstName == "firstname"); context.Users.Update( users, u => new User {FirstName = "newfirstname"}); Future Queries Build up a list of queries for the data that you need and the first time any of the results are accessed, all the data will retrieved in one round trip to the database server. Reducing the number of trips to the database is a great. Using this feature is as simple as appending .Future() to the end of your queries. To use the Future Queries, make sure to import the EntityFramework.Extensions namespace. Future queries are created with the following extension methods... Future() FutureFirstOrDefault() FutureCount() Sample // build up queries var q1 = db.Users .Where(t => t.EmailAddress == "[email protected]") .Future(); var q2 = db.Tasks .Where(t => t.Summary == "Test") .Future(); // this triggers the loading of all the future queries var users = q1.ToList(); In the example above, there are 2 queries built up, as soon as one of the queries is enumerated, it triggers the batch load of both queries. // base query var q = db.Tasks.Where(t => t.Priority == 2); // get total count var q1 = q.FutureCount(); // get page var q2 = q.Skip(pageIndex).Take(pageSize).Future(); // triggers execute as a batch int total = q1.Value; var tasks = q2.ToList(); In this example, we have a common senerio where you want to page a list of tasks. In order for the GUI to setup the paging control, you need a total count. With Future, we can batch together the queries to get all the data in one database call. Future queries work by creating the appropriate IFutureQuery object that keeps the IQuerable. The IFutureQuery object is then stored in IFutureContext.FutureQueries list. Then, when one of the IFutureQuery objects is enumerated, it calls back to IFutureContext.ExecuteFutureQueries() via the LoadAction delegate. ExecuteFutureQueries builds a batch query from all the stored IFutureQuery objects. Finally, all the IFutureQuery objects are updated with the results from the query. Audit Log The Audit Log feature will capture the changes to entities anytime they are submitted to the database. The Audit Log captures only the entities that are changed and only the properties on those entities that were changed. The before and after values are recorded. AuditLogger.LastAudit is where this information is held and there is a ToXml() method that makes it easy to turn the AuditLog into xml for easy storage. The AuditLog can be customized via attributes on the entities or via a Fluent Configuration API. Fluent Configuration // config audit when your application is starting up... var auditConfiguration = AuditConfiguration.Default; auditConfiguration.IncludeRelationships = true; auditConfiguration.LoadRelationships = true; auditConfiguration.DefaultAuditable = true; // customize the audit for Task entity auditConfiguration.IsAuditable<Task>() .NotAudited(t => t.TaskExtended) .FormatWith(t => t.Status, v => FormatStatus(v)); // set the display member when status is a foreign key auditConfiguration.IsAuditable<Status>() .DisplayMember(t => t.Name); Create an Audit Log var db = new TrackerContext(); var audit = db.BeginAudit(); // make some updates ... db.SaveChanges(); var log = audit.LastLog;

    Read the article

  • Storing non-content data in Orchard

    - by Bertrand Le Roy
    A CMS like Orchard is, by definition, designed to store content. What differentiates content from other kinds of data is rather subtle. The way I would describe it is by saying that if you would put each instance of a kind of data on its own web page, if it would make sense to add comments to it, or tags, or ratings, then it is content and you can store it in Orchard using all the convenient composition options that it offers. Otherwise, it probably isn't and you can store it using somewhat simpler means that I will now describe. In one of the modules I wrote, Vandelay.ThemePicker, there is some configuration data for the module. That data is not content by the definition I gave above. Let's look at how this data is stored and queried. The configuration data in question is a set of records, each of which has a number of properties: public class SettingsRecord { public virtual int Id { get; set;} public virtual string RuleType { get; set; } public virtual string Name { get; set; } public virtual string Criterion { get; set; } public virtual string Theme { get; set; } public virtual int Priority { get; set; } public virtual string Zone { get; set; } public virtual string Position { get; set; } } .csharpcode, .csharpcode pre { font-size: small; color: black; font-family: consolas, "Courier New", courier, monospace; background-color: #ffffff; /*white-space: pre;*/ } .csharpcode pre { margin: 0em; } .csharpcode .rem { color: #008000; } .csharpcode .kwrd { color: #0000ff; } .csharpcode .str { color: #006080; } .csharpcode .op { color: #0000c0; } .csharpcode .preproc { color: #cc6633; } .csharpcode .asp { background-color: #ffff00; } .csharpcode .html { color: #800000; } .csharpcode .attr { color: #ff0000; } .csharpcode .alt { background-color: #f4f4f4; width: 100%; margin: 0em; } .csharpcode .lnum { color: #606060; } Each property has to be virtual for nHibernate to handle it (it creates derived classed that are instrumented in all kinds of ways). We also have an Id property. The way these records will be stored in the database is described from a migration: public int Create() { SchemaBuilder.CreateTable("SettingsRecord", table => table .Column<int>("Id", column => column.PrimaryKey().Identity()) .Column<string>("RuleType", column => column.NotNull().WithDefault("")) .Column<string>("Name", column => column.NotNull().WithDefault("")) .Column<string>("Criterion", column => column.NotNull().WithDefault("")) .Column<string>("Theme", column => column.NotNull().WithDefault("")) .Column<int>("Priority", column => column.NotNull().WithDefault(10)) .Column<string>("Zone", column => column.NotNull().WithDefault("")) .Column<string>("Position", column => column.NotNull().WithDefault("")) ); return 1; } When we enable the feature, the migration will run, which will create the table in the database. Once we've done that, all we have to do in order to use the data is inject an IRepository<SettingsRecord>, which is what I'm doing from the set of helpers I put under the SettingsService class: private readonly IRepository<SettingsRecord> _repository; private readonly ISignals _signals; private readonly ICacheManager _cacheManager; public SettingsService( IRepository<SettingsRecord> repository, ISignals signals, ICacheManager cacheManager) { _repository = repository; _signals = signals; _cacheManager = cacheManager; } The repository has a Table property, which implements IQueryable<SettingsRecord> (enabling all kind of Linq queries) as well as methods such as Delete and Create. Here's for example how I'm getting all the records in the table: _repository.Table.ToList() And here's how I'm deleting a record: _repository.Delete(_repository.Get(r => r.Id == id)); And here's how I'm creating one: _repository.Create(new SettingsRecord { Name = name, RuleType = ruleType, Criterion = criterion, Theme = theme, Priority = priority, Zone = zone, Position = position }); In summary, you create a record class, a migration, and you're in business and can just manipulate the data through the repository that the framework is exposing. You even get ambient transactions from the work context.

    Read the article

  • How to convert a DataSet object into an ObjectContext (Entity Framework) object on the fly?

    - by Marcel
    Hi all, I have an existing SQL Server database, where I store data from large specific log files (often 100 MB and more), one per database. After some analysis, the database is deleted again. From the database, I have created both a Entity Framework Model and a DataSet Model via the Visual Studio designers. The DataSet is only for bulk importing data with SqlBulkCopy, after a quite complicated parsing process. All queries are then done using the Entity Framework Model, whose CreateQuery Method is exposed via an interface like this public IQueryable<TTarget> GetResults<TTarget>() where TTarget : EntityObject, new() { return this.Context.CreateQuery<TTarget>(typeof(TTarget).Name); } Now, sometimes my files are very small and in such a case I would like to omit the import into the database, but just have a an in-memory representation of the data, accessible as Entities. The idea is to create the DataSet, but instead of bulk importing, to directly transfer it into an ObjectContext which is accessible via the interface. Does this make sense? Now here's what I have done for this conversion so far: I traverse all tables in the DataSet, convert the single rows into entities of the corresponding type and add them to instantiated object of my typed Entity context class, like so MyEntities context = new MyEntities(); //create new in-memory context ///.... //get the item in the navigations table MyDataSet.NavigationResultRow dataRow = ds.NavigationResult.First(); //here, a foreach would be necessary in a true-world scenario NavigationResult entity = new NavigationResult { Direction = dataRow.Direction, ///... NavigationResultID = dataRow.NavigationResultID }; //convert to entities context.AddToNavigationResult(entity); //add to entities ///.... A very tedious work, as I would need to create a converter for each of my entity type and iterate over each table in the DataSet I have. Beware, if I ever change my database model.... Also, I have found out, that I can only instantiate MyEntities, if I provide a valid connection string to a SQL Server database. Since I do not want to actually write to my fully fledged database each time, this hinders my intentions. I intend to have only some in-memory proxy database. Can I do simpler? Is there some automated way of doing such a conversion, like generating an ObjectContext out of a DataSet object? P.S: I have seen a few questions about unit testing that seem somewhat related, but not quite exact.

    Read the article

  • Timeout Expired error Using LINQ

    - by Refracted Paladin
    I am going to sum up my problem first and then offer massive details and what I have already tried. Summary: I have an internal winform app that uses Linq 2 Sql to connect to a local SQL Express database. Each user has there own DB and the DB stay in sync through Merge Replication with a Central DB. All DB's are SQL 2005(sp2or3). We have been using this app for over 5 months now but recently our users are getting a Timeout expired. The timeout period elapsed prior to completion of the operation or the server is not responding. Detailed: The strange part is they get that in two differnt locations(2 differnt LINQ Methods) and only the first time they fire in a given time period(~5mins). One LINQ method is pulling all records that match a FK ID and then Manipulating them to form a Heirarchy View for a TreeView. The second is pulling all records that match a FK ID and dumping them into a DataGridView. The only things I can find in common with the 2 are that the first IS an IEnumerable and the second converts itself from IQueryable - IEnumerable - DataTable... I looked at the query's in Profiler and they 'seemed' normal. They are not very complicated querys. They are only pulling back 10 - 90 records, from one table. Any thoughts, suggestions, hints whatever would be greatly appreciated. I am at my wit's end on this.... public IList<CaseNoteTreeItem> GetTreeViewDataAsList(int personID) { var myContext = MatrixDataContext.Create(); var caseNotesTree = from cn in myContext.tblCaseNotes where cn.PersonID == personID orderby cn.ContactDate descending, cn.InsertDate descending select new CaseNoteTreeItem { CaseNoteID = cn.CaseNoteID, NoteContactDate = Convert.ToDateTime(cn.ContactDate). ToShortDateString(), ParentNoteID = cn.ParentNote, InsertUser = cn.InsertUser, ContactDetailsPreview = cn.ContactDetails.Substring(0, 75) }; return caseNotesTree.ToList<CaseNoteTreeItem>(); } AND THIS ONE public static DataTable GetAllCNotes(int personID) { using (var context = MatrixDataContext.Create()) { var caseNotes = from cn in context.tblCaseNotes where cn.PersonID == personID orderby cn.ContactDate select new { cn.ContactDate, cn.ContactDetails, cn.TimeSpentUnits, cn.IsCaseLog, cn.IsPreEnrollment, cn.PresentAtContact, cn.InsertDate, cn.InsertUser, cn.CaseNoteID, cn.ParentNote }; return caseNotes.ToList().CopyLinqToDataTable(); } }

    Read the article

  • RIA Services Repository Save does not work!?

    - by Savvas Sopiadis
    Hello everybody! Doing my first SL4 MVVM RIA based application and i ran into the following situation: updating a record (EF4,NO-POCOS!!) in the SL-client seems to take place, but values in the dbms are unchanged. Debugging with Fiddler the message on save is (amongst others): EntityActions.nil? b9http://schemas.microsoft.com/2003/10/Serialization/Arrays^HasMemberChanges?^Id?^ Operation?Update I assume that this says only: hey! the dbms should do an update on this record, AND nothing more! Is that right?! I 'm using a generic repository like this: public class Repository<T> : IRepository<T> where T : class { IObjectSet<T> _objectSet; IObjectContext _objectContext; public Repository(IObjectContext objectContext) { this._objectContext = objectContext; _objectSet = objectContext.CreateObjectSet<T>(); } public IQueryable<T> AsQueryable() { return _objectSet; } public IEnumerable<T> GetAll() { return _objectSet.ToList(); } public IEnumerable<T> Find(Expression<Func<T, bool>> where) { return _objectSet.Where(where); } public T Single(Expression<Func<T, bool>> where) { return _objectSet.Single(where); } public T First(Expression<Func<T, bool>> where) { return _objectSet.First(where); } public void Delete(T entity) { _objectSet.DeleteObject(entity); } public void Add(T entity) { _objectSet.AddObject(entity); } public void Attach(T entity) { _objectSet.Attach(entity); } public void Save() { _objectContext.SaveChanges(); } } The DomainService Update Method is the following: [Update] public void UpdateCulture(Culture currentCulture) { if (currentCulture.EntityState == System.Data.EntityState.Detached) { this.cultureRepository.Attach(currentCulture); } this.cultureRepository.Save(); } I know that the currentCulture-Entity is detached. What confuses me (amongst other things) is this: is the _objectContext still alive? (which means it "will be"??? aware of the changes made to record, so simply calling Attach() and then Save() should be enough!?!?) What am i missing? Development Environment: VS2010RC - Entity Framework 4 (no POCOs) Thanks in advance

    Read the article

  • ASP NET MVC (loading data from database)

    - by rah.deex
    hi experts, its me again... i have some code like this.. using System; using System.Collections.Generic; using System.Linq; using System.Web; namespace MvcGridSample.Models { public class CustomerService { private List<SVC> Customers { get { List<SVC> customers; if (HttpContext.Current.Session["Customers"] != null) { customers = (List<SVC>) HttpContext.Current.Session["Customers"]; } else { //Create customer data store and save in session customers = new List<SVC>(); InitCustomerData(customers); HttpContext.Current.Session["Customers"] = customers; } return customers; } } public SVC GetByID(int customerID) { return this.Customers.AsQueryable().First(customer => customer.seq_ == customerID); } public IQueryable<SVC> GetQueryable() { return this.Customers.AsQueryable(); } public void Add(SVC customer) { this.Customers.Add(customer); } public void Update(SVC customer) { } public void Delete(int customerID) { this.Customers.RemoveAll(customer => customer.seq_ == customerID); } private void InitCustomerData(List<SVC> customers) { customers.Add(new SVC { ID = 1, FirstName = "John", LastName = "Doe", Phone = "1111111111", Email = "[email protected]", OrdersPlaced = 5, DateOfLastOrder = DateTime.Parse("5/3/2007") }); customers.Add(new SVC { ID = 2, FirstName = "Jane", LastName = "Doe", Phone = "2222222222", Email = "[email protected]", OrdersPlaced = 3, DateOfLastOrder = DateTime.Parse("4/5/2008") }); customers.Add(new SVC { ID = 3, FirstName = "John", LastName = "Smith", Phone = "3333333333", Email = "[email protected]", OrdersPlaced = 25, DateOfLastOrder = DateTime.Parse("4/5/2000") }); customers.Add(new SVC { ID = 4, FirstName = "Eddie", LastName = "Murphy", Phone = "4444444444", Email = "[email protected]", OrdersPlaced = 1, DateOfLastOrder = DateTime.Parse("4/5/2003") }); customers.Add(new SVC { ID = 5, FirstName = "Ziggie", LastName = "Ziggler", Phone = null, Email = "[email protected]", OrdersPlaced = 0, DateOfLastOrder = null }); customers.Add(new SVC { ID = 6, FirstName = "Michael", LastName = "J", Phone = "666666666", Email = "[email protected]", OrdersPlaced = 5, DateOfLastOrder = DateTime.Parse("12/3/2007") }); } } } those codes is an example that i've got from the internet.. in that case, the data is created and saved in session before its shown.. the things that i want to ask is how if i want to load the data from table? i'am a newbie here.. please help :) thank b4 for advance..

    Read the article

  • Data Access Layer - static list objects and caching

    - by Truegilly
    Hello, i am devloping a site using .net MVC i have a data access layer which basically consists of static list objects that are created from data within my database. The method that rebuilds this data first clears all the list objects. Once they are empty it then add the data. Here is an example of one of the lists im using. its a method which generates all the UK postcodes. there are about 50 methods similar to this in my application that return all sorts of information, such as towns, regions, members, emails etc. public static List<PostCode> AllPostCodes = new List<PostCode>(); when the rebuild method is called it first clears the list. ListPostCodes.AllPostCodes.Clear(); next it re-bulilds the data, by calling the GetAllPostCodes() method /// <summary> /// static method that returns all the UK postcodes /// </summary> public static void GetAllPostCodes() { using (fab_dataContextDataContext db = new fab_dataContextDataContext()) { IQueryable AllPostcodeData = from data in db.PostCodeTables select data; IDbCommand cmd = db.GetCommand(AllPostcodeData); SqlDataAdapter adapter = new SqlDataAdapter(); adapter.SelectCommand = (SqlCommand)cmd; DataSet dataSet = new DataSet(); cmd.Connection.Open(); adapter.FillSchema(dataSet, SchemaType.Source); adapter.Fill(dataSet); cmd.Connection.Close(); // crete the objects foreach (DataRow row in dataSet.Tables[0].Rows) { PostCode postcode = new PostCode(); postcode.ID = Convert.ToInt32(row["PostcodeID"]); postcode.Outcode = row["OutCode"].ToString(); postcode.Latitude = Convert.ToDouble(row["Latitude"]); postcode.Longitude = Convert.ToDouble(row["Longitude"]); postcode.TownID = Convert.ToInt32(row["TownID"]); AllPostCodes.Add(postcode); postcode = null; } } } The rebuild occurs every 1 hour. this ensures that every 1 hour the site will have fresh set of cached data. the issue ive got is that occasionally if during a rebuild, the server will be hit by a request and an exception is thrown. The exception is "Index was outside the bounds of the array." it is due to when a list is being cleared. ListPostCodes.AllPostCodes.Clear(); - // throws exception - although its not always in regard to this list. Once this exception is thrown application dies, All users are affected. I have to restart the server to fix it. i have 2 questions... If i utilise caching instead of static objects would this help ? Is there any way i can say "while the rebuild is taking place, wait for it to complete until accepting requests" any help is most appricaiated ;) truegilly

    Read the article

< Previous Page | 12 13 14 15 16 17 18  | Next Page >