Search Results

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

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

  • Translating Where() to sql

    - by MBoros
    Hi. I saw DamienG's article (http://damieng.com/blog/2009/06/24/client-side-properties-and-any-remote-linq-provider) in how to map client properties to sql. i ran throgh this article, and i saw great potential in it. Definitely mapping client properties to SQL is an awesome idea. But i wanted to use this for something a bit more complicated then just concatenating strings. Atm we are trying to introduce multilinguality to our Business objects, and i hoped we could leave all the existing linq2sql queries intact, and just change the code of the multilingual properties, so they would actually return the given property in the CurrentUICulture. The first idea was to change these fields to XMLs, and then try the Object.Property.Elements().Where(...), but it got stuck on the Elements(), as it couldnt translate it to sql. I read somewhere that XML fields are actually regarded as strings, and only on the app server they become XElements, so this way the filtering would be on the app server anyways, not the DB. Fair point, it wont work like this. Lets try something else... SO the second idea was to create a PolyGlots table (name taken from http://weblogic.sys-con.com/node/102698?page=0,1), a PolyGlotTranslations table and a Culture table, where the PolyGlots would be referenced from each internationalized property. This way i wanted to say for example: private static readonly CompiledExpression<Announcement, string> nameExpression = DefaultTranslationOf<Announcement> .Property(e => e.Name) .Is(e=> e.NamePolyGlot.PolyGlotTranslations .Where(t=> t.Culture.Code == Thread.CurrentThread.CurrentUICulture.Name) .Single().Value ); now unfortunately here i get an error that the Where() function cannot be translated to sql, what is a bit disappointing, as i was sure it will go through. I guess it is failing, cause the IEntitySet is basically an IEnumerable, not IQueryable, am i right? Is there another way to use the compiledExpressions class to achieve this goal? Any help appreciated.

    Read the article

  • Using LinqExtender to make OData feed fails

    - by BurningIce
    A pretty simple question, has anyone here tried to make a OData feed based on a IQueryable created with LinqExtender? I have created a simple Linq-provider that supports Where, Select, OrderBy and Take and wanted to expose it as an OData Feed. I keep getting an error though, and the Exception is a NullReference with the following StackTrace at System.Data.Services.Serializers.Serializer.GetObjectKey(Object resource, IDataServiceProvider provider, String containerName) at System.Data.Services.Serializers.Serializer.GetUri(Object resource, IDataServiceProvider provider, ResourceContainer container, Uri absoluteServiceUri) at System.Data.Services.Serializers.SyndicationSerializer.WriteEntryElement(IExpandedResult expanded, Object element, Type expectedType, Uri absoluteUri, String relativeUri, SyndicationItem target) at System.Data.Services.Serializers.SyndicationSerializer.<DeferredFeedItems>d__0.MoveNext() at System.ServiceModel.Syndication.Atom10FeedFormatter.WriteItems(XmlWriter writer, IEnumerable`1 items, Uri feedBaseUri) at System.ServiceModel.Syndication.Atom10FeedFormatter.WriteFeedTo(XmlWriter writer, SyndicationFeed feed, Boolean isSourceFeed) at System.ServiceModel.Syndication.Atom10FeedFormatter.WriteFeed(XmlWriter writer) at System.ServiceModel.Syndication.Atom10FeedFormatter.WriteTo(XmlWriter writer) at System.Data.Services.Serializers.SyndicationSerializer.WriteTopLevelElements(IExpandedResult expanded, IEnumerator elements, Boolean hasMoved) at System.Data.Services.Serializers.Serializer.WriteRequest(IEnumerator queryResults, Boolean hasMoved) at System.Data.Services.ResponseBodyWriter.Write(Stream stream) I've kinda narrowed it down to a issue where LinqExtender wraps every returned object, so that my object actually inherits itself - thats at least how it looks like in the debugger. These two queries are basicly the same. The first is the legacy-api where the OrderBy and Select is regular Linq to Objects. The second query is a "real" linq-provider made with LinqExtender. var db = CalendarDataProvider.GetCalendarEntriesByDate(DateTime.Now, DateTime.Now.AddMonths(1), Guid.Empty) .OrderBy(o => o.Title) .Select(o => new ODataCalendarEntry(o)); var query = new ODataCalendarEntryQuery() .Where(o => o.Start > DateTime.Now && o.End < DateTime.Now.AddMonths(1)) .OrderBy(o => o.Title); When returning db for the OData feed everything is fine, but returning query throws a NullRefenceException. I've tried all kind of tricks and even tried to project all the data into a new object like this, but still the same error return query.Select(o => new ODataCalendarEntry { Title = o.Title, Start = o.Start, End = o.End, Name = o.Name });

    Read the article

  • Partial Evaluation of ConstantExpression in ExpressionTreeVisitor

    - by Andrew Theken
    Hi all, I am not an Expression Tree master by any stretch of the imagination, what I have is code that looks like this: int external = 10; using(var session = new Session()) { session.Add(new Product { Name = "test1", Price = 20 }); session.Add(new Product {Name = "test", Price = 10}); var product = session.Products.Where(p => p.Price == external).FirstOrDefault(); Assert.Equal(10, product.Price); } Session implements all the IQueryProvider, IQueryable interfaces you'd come to expect from a LINQ Provider. When I execute the query, everything goes to plan until I read the ConstantExpression for "external", at which point, I am at a loss as to how to move forward because: //constant is ConstantExpression for "external" on the right side of the "p.Price == external" expression above. var t = constant.GetType(); //evaluates to class called "<>c__DisplayClass2" - with a member named "external" that has the value 10. The question is basically.. How can I just access the value of the member "external" - is there a way to accomplish this without using reflection? or am I cooked? What am I missing?

    Read the article

  • How do I add ROW_NUMBER to a LINQ query or Entity?

    - by Whozumommy
    I'm stumped by this easy data problem. I'm using the Entity framework and have a database of products. My results page returns a paginated list of these products. Right now my results are ordered by the number of sales of each product, so my code looks like this: return Products.OrderByDescending(u => u.Sales.Count()); This returns an IQueryable dataset of my entities, sorted by the number of sales. I want my results page to show the rank of each product (in the dataset). My results should look like this: Page #1 1. Bananas 2. Apples 3. Coffee Page #2 4. Cookies 5. Ice Cream 6. Lettuce I'm expecting that I just want to add a column in my results using the SQL ROW_NUMBER variable...but I don't know how to add this column to my results datatable. My resulting page does contain a foreach loop, but since I'm using a paginated set I'm guessing using that number to fake a ranking number would NOT be the best approach. So my question is, how do I add a ROW_NUMBER column to my query results in this case?

    Read the article

  • How do I unit test controllers for an asp.net mvc site that uses StructureMap and NHibernate?

    - by Jim Geurts
    I have an asp.net mvc2 application that is using StructureMap 2.6 and NHibernate 3.x. I would like to add unit tests to the application but am sort of at a loss for how to accomplish it. Say I have a basic controller called Posts that has an action called Index. The controller looks something like: public class PostsController : Controller { private readonly IPostService _postService; public PostsController(IPostService postService) { _postService = postService; } public ActionResult Index() { return View(_postService.QueryOver<Post>().Future()); } } If I wanted to create an nunit test that would verify that the index action is returning all of the posts, how do I go about that? If mocking is recommended, do you just assume that interaction with the database will work? Sorry for asking such a broad question, but my web searches haven't turned up anything decent for how to unit test asp.net mvc actions that use StructureMap (or any other IOC) and NHibernate. btw, if you don't like that I return a QueryOver object from my post service, pretend it is an IQueryable object. I'm using it essentially in the same way.

    Read the article

  • entity framework - getting null exception using foreign key

    - by Nick
    Having some trouble with what should be a very simple scenario. For example purposes, I have two tables: -Users -Comments There is a one-to-many relationship set up for this; there is a foreign key from Comments.CommentorID to Users.UserID. When I do the LINQ query and try to bind to a DataList, I get a null exception. Here is the code: FKMModel.FKMEntities ctx = new FKMModel.FKMEntities(); IQueryable<Comment> CommentQuery = from x in ctx.Comment where x.SiteID == 101 select x; List<Comment> Comments = CommentQuery.ToList(); dl_MajorComments.DataSource = Comments; dl_MajorComments.DataBind(); In the ASPX page, I have the following as an ItemTemplate (I simplified it and took out the styling, etc, for purposes of posting here since it's irrelevant): <div> <%# ((FKMModel.Comment)Container.DataItem).FKMUser.Username %> <%# ((FKMModel.Comment)Container.DataItem).CommentDate.Value.ToShortDateString() %> <%# ((FKMModel.Comment)Container.DataItem).CommentTime %> </div> The exception occurs on the first binding (FKMUser.Username). Since the foreign key is set up, I should have no problem accessing any properties from the Users table. Intellisense set up the FKMUser navigation property and it knows the properties of that foreign table. What is going on here??? Thanks, Nick

    Read the article

  • ASP NET MVC Error In Function

    - by rah.deex
    hello it's me again... thx b4 to experts who have provided solutions to my question.. now i've got some trouble again, would you please halp me... this is my code (i've got this sample from the internet n i try to modify it) :) private void FillGridData() { //IQueryable<SVC> query = _customerService.GetQueryable(); _dataContext = new dbServiceModelDataContext(); var query = from m in _dataContext.SVCs select m; query = AddQuerySearchCriteria(query, _grid.SearchForm); int totalRows = query.Count(); _grid.Pager.Init(totalRows); if (totalRows == 0) { _grid.Data = new List<SVC>(); return; } query = AddQuerySorting(query, _grid.Sorter); query = AddQueryPaging(query, _grid.Pager); List<SVC> customers = query.ToList(); //***ERROR IN HERE***// _grid.Data = customers; } the error says "Cannot order by type 'System.Object'.", what is the matter? do you have solution for me, please...

    Read the article

  • ASP NET MVC Error In Funcion

    - by rah.deex
    hello it's me again... thx b4 to experts who have provided solutions to my question.. now i've got some trouble again, would you please halp me... this is my code (i've got this sample from the internet n i try to modify it) :) private void FillGridData() { //IQueryable<SVC> query = _customerService.GetQueryable(); _dataContext = new dbServiceModelDataContext(); var query = from m in _dataContext.SVCs select m; query = AddQuerySearchCriteria(query, _grid.SearchForm); int totalRows = query.Count(); _grid.Pager.Init(totalRows); if (totalRows == 0) { _grid.Data = new List<SVC>(); return; } query = AddQuerySorting(query, _grid.Sorter); query = AddQueryPaging(query, _grid.Pager); List<SVC> customers = query.ToList(); //***ERROR IN HERE***// _grid.Data = customers; } the error says "Cannot order by type 'System.Object'.", what is the matter? do you have solution for me, please...

    Read the article

  • LINQ to SQL - Why can't you use a WHERE after an ORDER BY?

    - by MCS
    The following code: // select all orders var orders = from o in FoodOrders where o.STATUS = 1 order by o.ORDER_DATE descending select o; // if customer id is specified, only select orders from specific customer if (customerID!=null) { orders = orders.Where(o => customerID.Equals(o.CUSTOMER_ID)); } gives me the following error: Cannot implicitly convert type 'System.Linq.IQueryable' to 'System.Linq.IOrderedQueryable'. An explicit conversion exists (are you missing a cast?) I fixed the error by doing the sorting at the end: // select all orders var orders = from o in FoodOrders where o.STATUS = 1 select o; // if customer id is specified, only select orders from specific customer if (customerID!=null) { orders = orders.Where(o => customerID.Equals(o.CUSTOMER_ID)); } // I'm forced to do the ordering here orders = orders.OrderBy(o => o.ORDER_DATE).Reverse(); But I'm wondering why is this limitation in place? What's the reason the API was designed in such a way that you can't add a where constraint after using an order by operator?

    Read the article

  • LINQ Query using UDF that receives parameters from the query

    - by Ben Fidge
    I need help using a UDF in a LINQ which calculates a users position from a fixed point. int pointX = 567, int pointY = 534; // random points on a square grid var q = from n in _context.Users join m in _context.GetUserDistance(n.posY, n.posY, pointX, pointY, n.UserId) on n.UserId equals m.UserId select new User() { PosX = n.PosX, PosY = n.PosY, Distance = m.Distance, Name = n.Name, UserId = n.UserId }; The GetUserDistance is just a UDF that returns a single row in a TVP with that users distance from the points deisgnated in pointX and pointY variables, and the designer generates the following for it: [global::System.Data.Linq.Mapping.FunctionAttribute(Name="dbo.GetUserDistance", IsComposable=true)] public IQueryable<GetUserDistanceResult> GetUserDistance([global::System.Data.Linq.Mapping.ParameterAttribute(Name="X1", DbType="Int")] System.Nullable<int> x1, [global::System.Data.Linq.Mapping.ParameterAttribute(Name="X2", DbType="Int")] System.Nullable<int> x2, [global::System.Data.Linq.Mapping.ParameterAttribute(Name="Y1", DbType="Int")] System.Nullable<int> y1, [global::System.Data.Linq.Mapping.ParameterAttribute(Name="Y2", DbType="Int")] System.Nullable<int> y2, [global::System.Data.Linq.Mapping.ParameterAttribute(Name="UserId", DbType="Int")] System.Nullable<int> userId) { return this.CreateMethodCallQuery<GetUserDistanceResult>(this, ((MethodInfo)(MethodInfo.GetCurrentMethod())), x1, x2, y1, y2, userId); } when i try to compile i get The name 'n' does not exist in the current context

    Read the article

  • Controller class not available in Add View ASP.NET MVC

    - by Tassadaque
    Hi I have created the following controller i want to add view that should have the data access class UserMagnament.Controller.menuitems but when i add view by right clicking on view folder,it is not showing "UserMagnament.Controller.menuitems" in add data class using System; using System.Collections.Generic; using System.Linq; using System.Web; using System.Web.Mvc; using UserManagement.Models; namespace UserManagement.Controllers { public class menuitems { EvoLetDataContext db1 = new EvoLetDataContext(); public menuitems() { } public IQueryable<UMUserType> menuitems() { return db1.UMUserTypes; //this.Packages = _SysPackage; //this.Modules = _SysModule; } public List<SysPackage> Packages { get; private set; } public List<SysModule> Modules { get; private set; } } public class Default1Controller : Controller { // // GET: /Default1/ public ActionResult Index() { return View(new menuitems()); } } }

    Read the article

  • asp.net mvc select change redirect to Action

    - by mazhar kaunain baig
    I am correctly passing the action name from the Controller to the paging class and then using select list i want to redirect to that action. at this moment it is appending to the current url.i want the correct way of redirecting to the controller action manageUser using select list below What should we have here in Model.COntroller . ControllerName/ActionName/ or Just ActionName <select id="paging" onchange="location.href='<%= Model.Controller %>'+this.value"> <% for (int i = 1; i <= Model.TotalPages; i++) { %> <option id=<%=i %>><%=i %></option> <% } %> </select> public class PaginatedList<T> : List<T> { public string Controller { get; private set; } public PaginatedList(IQueryable<T> source, int pageIndex, int pageSize,string Cont) { Controller = Cont; // here is the controller } } Controller public ActionResult ManageUser(int? page) { const int pageSize = 5; var AllUser = UserRepository.GetAllUser(); var paginatedUsers = new PaginatedList<Users>(AllUser, page ?? 1, pageSize,"ManageUser/Page/"); return View(paginatedUsers); }

    Read the article

  • Complex LINQ paging algorithm

    - by sharepointmonkey
    We have a list of projects that may or may not have a collection of subprojects. Our report needs to contain all the projects except those that are the parent project of a subproject. I need to page this into pages of, say, 25 rows. But if subprojects appear on that page then ALL the subprojects of that project must appear on the same page. So more than 25 items may appear if necessary. I've got as far as var pagedProjects = db.Projects.Where(x => !x.SubProjects.Any()).Skip( (pageNo -1) * pageSize).Take(pageSize); Obviously, this fails the second part of the requirements. As a further pain in the arse, I need to have a pager control on the report. So I'll need to be able to calculate the total number of pages. I could loop through the whole table of projects but the performance will suffer. Can anybody come up with a paged solution? EDIT - I should probably mention that SubProjects joins back onto Projects via a selfreferencing foreign key so the whole lot comes back as an IQueryable<Project>.

    Read the article

  • LINQ to SQL - How to efficiently do either an AND or an OR search for multiple criteria

    - by Dan Diplo
    I have an ASP.NET MVC site (which uses Linq To Sql for the ORM) and a situation where a client wants a search facility against a bespoke database whereby they can choose to either do an 'AND' search (all criteria match) or an 'OR' search (any criteria match). The query is quite complex and long and I want to know if there is a simple way I can make it do both without having to have create and maintain two different versions of the query. For instance, the current 'AND' search looks something like this (but this is a much simplified version): private IQueryable<SampleListDto> GetSampleSearchQuery(SamplesCriteria criteria) { var results = from r in Table where (r.Id == criteria.SampleId) && (r.Status.SampleStatusId == criteria.SampleStatusId) && (r.Job.JobNumber.StartsWith(criteria.JobNumber)) && (r.Description.Contains(criteria.Description)) select r; } I could copy this and replace the && with || operators to get the 'OR' version, but feel there must be a better way of achieving this. Does anybody have any suggestions how this can be achieved in an efficient and flexible way that is easy to maintain? Thanks.

    Read the article

  • Organizing Eager Queries in an ObjectContext

    - by Nix
    I am messing around with Entity Framework 3.5 SP1 and I am trying to find a cleaner way to do the below. I have an EF model and I am adding some Eager Loaded entities and i want them all to reside in the "Eager" property in the context. We originally were just changing the entity set name, but it seems a lot cleaner to just use a property, and keep the entity set name in tact. Example: Context - EntityType - AnotherType - Eager (all of these would have .Includes to pull in all assoc. tables) - EntityType - AnotherType Currently I am using composition but I feel like there is an easier way to do what I want. namespace Entities{ public partial class TestObjectContext { EagerExtensions Eager { get;set;} public TestObjectContext(){ Eager = new EagerExtensions (this); } } public partial class EagerExtensions { TestObjectContext context; public EagerExtensions(TestObjectContext _context){ context = _context; } public IQueryable<TestEntity> TestEntity { get { return context.TestEntity .Include("TestEntityType") .Include("Test.Attached.AttachedType") .AsQueryable(); } } } } public class Tester{ public void ShowHowIWantIt(){ TestObjectContext context= new TestObjectContext(); var query = from a in context.Eager.TestEntity select a; } }

    Read the article

  • LinqToSql Select to a class then do more queries

    - by fyjham
    I have a LINQ query running with multiple joins and I want to pass it around as an IQueryable<T> and apply additional filters in other methods. The problem is that I can't work out how to pass around a var data type and keep it strongly typed, and if I try to put it in my own class (EG: .Select((a,b) => new MyClass(a,b))) I get errors when I try to add later Where clauses because my class has no translations into SQL. Is there any way I can do one of the following: Make my class map to SQL? Make the var data-type implement an interface (So I can pass it round as though it's that)? Something I haven't though of that'll solve my issue? Example: public void Main() { using (DBDataContext context = new DBDataContext()) { var result = context.TableAs.Join( context.TableBs, a => a.BID, b => b.ID, (a,b) => new {A = a, B = b} ); result = addNeedValue(result, 4); } } private ???? addNeedValue(???? result, int value) { return result.Where(r => r.A.Value == value); } PS: I know in my example I can flatten out the function easily, but in the real thing it'd be an absolute mess if I tried.

    Read the article

  • .Net Entity Framework & POCO ... querying full table problem

    - by Chris Klepeis
    I'm attempting to implement a repository pattern with my poco objects auto generated from my edmx. In my repository class, I have: IObjectSet<E> _objectSet; private IObjectSet<E> objectSet { get { if (_objectSet == null) { _objectSet = this._context.CreateObjectSet<E>(); } return _objectSet; } } public IQueryable<E> GetQuery(Func<E, bool> where) { return objectSet.Where(where).AsQueryable<E>(); } public IList<E> SelectAll(Func<E, bool> where) { return GetQuery(where).ToList(); } Where E is the one of my POCO classes. When I trace the database and run this: IList<Contact> c = contactRepository.SelectAll(r => r.emailAddress == "[email protected]"); It shows up in the sql trace as a select for everything in my Contact table. Where am I going wrong here? Is there a better way to do this? Does an objectset not lazy load... so it omitted the where clause? This is the article I read which said to use objectSet's... since with POCO, I do not have EntityObject's to pass into "E" http://devtalk.dk/CommentView,guid,b5d9cad2-e155-423b-b66f-7ec287c5cb06.aspx

    Read the article

  • Breeze Expand not working on WebAPI with EF

    - by Rodney
    I have published a WebAPI service which returns a list of items. I am implementing Breeze and have managed to get it basically working with filtering/sorting. However, the Expand is not working. http://www.ftter.com/desktopmodules/framework/api/dare/dares/?$filter=DareId%20eq%2010&expand%20eq%20ToUser You can see the ToUserId ForeignKey in the response above, but the ToUser properties are NULL (the user definitely exists) You can see the ToUser EF navigation property in the metadata. When I use .Include on the server side I can populate it with EF, but I don't want to do this. [HttpGet] [Queryable(AllowedQueryOptions = AllowedQueryOptions.All)] public HttpResponseMessage Dares() { var response = Request.CreateResponse(HttpStatusCode.OK, (IQueryable<Dare>)contextProvider.Context.Dares); return ControllerUtilities.GetResponseWithCorsHeader(response); } and here is the generated class from my EF model (using Database First) public partial class Dare { public int DareId { get; set; } public int ToUserId { get; set; } public virtual User ToUser { get; set; } }

    Read the article

  • web ui controls and ASP.NET MVC

    - by ognjenb
    Why will not fill View page of this controller method public ActionResult Person() { testEntities6 testPersons = new testEntities6(); IQueryable<person> persons; DropDownLst.Items.Clear(); DropDownLst.Items.Add("proba"); persons = from i in testPersons.person select i; return View(persons); } and include namespaces: using System; using System.Collections.Generic; using System.Linq; using System.Web; using System.Web.Mvc; using System.Web.Mvc.Ajax; using MvcKVteam.Models; using System.Web.UI; using System.Web.UI.WebControls; using System.Web.UI.WebControls.WebParts; using System.Web.UI.HtmlControls; In view page I put this code: <asp:DropDownList ID="IbekoIngDropDownLst" runat="server"> </asp:DropDownList>

    Read the article

  • Linq In Clause & Predicate building

    - by Michael G
    I have two tables. Report and ReportData. ReportData has a constraint ReportID. How can I write my linq query to return all Report objects where the predicate conditions are met for ReportData? Something like this in SQL: SELECT * FROM Report as r Where r.ServiceID = 3 and r.ReportID IN (Select ReportID FROM ReportData WHERE JobID LIKE 'Something%') This is how I'm building my predicate: Expression<Func<ReportData, bool>> predicate = PredicateBuilder.True<ReportData>(); predicate = predicate.And(x => x.JobID.StartsWith(QueryConfig.Instance.DataStreamName)); var q = engine.GetReports(predicate, reportsDataContext); reports = q.ToList(); This is my query construction at the moment: public override IQueryable<Report> GetReports(Expression<Func<ReportData, bool>> predicate, LLReportsDataContext reportDC) { if (reportDC == null) throw new ArgumentNullException("reportDC"); var q = reportDC.ReportDatas.Where(predicate).Where(r => r.ServiceID.Equals(1)).Select(r => r.Report); return q; }

    Read the article

  • Using LINQ on observable with GroupBy and Sum aggregate

    - by Mark Oates
    I have the following block of code which works fine; var boughtItemsToday = (from DBControl.MoneySpent bought in BoughtItemDB.BoughtItems select bought); BoughtItems = new ObservableCollection<DBControl.MoneySpent>(boughtItemsToday); It returns data from my MoneySpent table which includes ItemCategory, ItemAmount, ItemDateTime. I want to change it to group by ItemCategory and ItemAmount so I can see where I am spending most of my money, so I created a GroupBy query, and ended up with this; var finalQuery = boughtItemsToday.AsQueryable().GroupBy(category => category.ItemCategory); BoughtItems = new ObservableCollection<DBControl.MoneySpent>(finalQuery); Which gives me 2 errors; Error 1 The best overloaded method match for 'System.Collections.ObjectModel.ObservableCollection.ObservableCollection(System.Collections.Generic.List)' has some invalid arguments Error 2 Argument 1: cannot convert from 'System.Linq.IQueryable' to 'System.Collections.Generic.List' And this is where I'm stuck! How can I use the GroupBy and Sum aggregate function to get a list of my categories and the associated spend in 1 LINQ query?! Any help/suggestions gratefully received. Mark

    Read the article

  • Using Subsonic 3.0 Advanced Templates

    - by umit
    Hi all, I've been trying to use Subsonic Advanced Templates in a project for a while but most of the time I find myself writing a Stored Procedure as I can't find a proper way of doing it in code. Subsonic created corresponding objects for my DB tables and for foreign keys it created IQueryable fields inside each object. These fields are not loaded by default and a new SQL query is executed when you access them. 1- Is there a way to get all data in one query (deep load)? Also these fields can not be assigned. So when I want to create an object in a maintenance page, I can't put all the data into this object before saving it in DB: Post post = new Post(); //get photos for this post IList<PostPhoto> postPhotos = GetPostPhotos(); post.PostPhotos = postPhotos; 2- Is it possible to have one Post object with all fields set from user input? Think of the Post object above and assume I've successfully assigned its fields. Now I need to save it to the DB. 3- Is using BatchQuery the only way to do it in one query? If I have 4 photos in PostPhotos field; 2 of them previously saved and 2 of them new, can I use the Update method to handle both the adding and updating of these photos? Any ideas or links are appreciated. Cheers...

    Read the article

  • EF/LINQ: Where() against a property of a subtype

    - by ladenedge
    I have a set of POCOs, all of which implement the following simple interface: interface IIdObject { int Id { get; set; } } A subset of these POCOs implement this additional interface: interface IDeletableObject : IIdObject { bool IsDeleted { get; set; } } I have a repository hierarchy that looks something like this: IRepository<T <: BasicRepository<T <: ValidatingRepository<T (where T is IIdObject) I'm trying to add a FilteringRepository to the hierarchy such that all of the POCOs that implement IDeletableObject have a Where(p => p.IsDeleted == false) filter applied before any other queries take place. My goal is to avoid duplicating the hierarchy solely for IDeletableObjects. My first attempt looked like this: public override IQueryable<T> Query() { return base.Query().Where(t => ((IDeletableObject)t).IsDeleted == false); } This works well with LINQ to Objects, but when I switch to an EF backend I get: "LINQ to Entities only supports casting Entity Data Model primitive types." I went on to try some fancier parameterized solutions, but they ultimately failed because I couldn't make T covariant in the following case for some reason I don't quite understand: interface IQueryFilter<out T> // error { Expression<Func<T, bool>> GetFilter(); } I'd be happy to go into more detail on my more complicated solutions if it would help, but I think I'll stop here for now in hope that someone might have an idea for me to try. Thanks very much in advance!

    Read the article

  • How to Update with LINQ?

    - by DaveDev
    currently, I'm doing an update similar to as follows, because I can't see a better way of doing it. I've tried suggestions that I've read in blogs but none work, such as http://msdn.microsoft.com/en-us/library/bb425822.aspx and http://weblogs.asp.net/scottgu/archive/2007/05/19/using-linq-to-sql-part-1.aspx Maybe these do work and I'm missing some point. Has anyone else had luck with them? // please note this isn't the actual code. // I've modified it to clarify the point I wanted to make // and also I didn't want to post our code here! public bool UpdateMyStuff(int myId, List<int> funds) { // get MyTypes that correspond to the ID I want to update IQueryable<MyType> myTypes = database.MyTypes.Where(xx => xx.MyType_MyId == myId); // delete them from the database foreach (db.MyType mt in myTypes) { database.MyTypes.DeleteOnSubmit(mt); } database.SubmitChanges(); // create a new row for each item I wanted to update, and insert it foreach (int fund in funds) { database.MyType mt = new database.MyType { MyType_MyId = myId, fund_id = fund }; database.MyTypes.InsertOnSubmit(mt); } // try to commit the insert try { database.SubmitChanges(); return true; } catch (Exception) { return false; throw; } } Unfortunately, there isn't a database.MyTypes.Update() method so I don't know a better way to do it. Can sombody suggest what I could do? Thanks. ..as a side note, why isn't there an Update() method?

    Read the article

  • DataSets to POCOs - an inquiry regarding DAL architecture

    - by alexsome
    Hello all, I have to develop a fairly large ASP.NET MVC project very quickly and I would like to get some opinions on my DAL design to make sure nothing will come back to bite me since the BL is likely to get pretty complex. A bit of background: I am working with an Oracle backend so the built-in LINQ to SQL is out; I also need to use production-level libraries so the Oracle EF provider project is out; finally, I am unable to use any GPL or LGPL code (Apache, MS-PL, BSD are okay) so NHibernate/Castle Project are out. I would prefer - if at all possible - to avoid dishing out money but I am more concerned about implementing the right solution. To summarize, there are my requirements: Oracle backend Rapid development (L)GPL-free Free I'm reasonably happy with DataSets but I would benefit from using POCOs as an intermediary between DataSets and views. Who knows, maybe at some point another DAL solution will show up and I will get the time to switch it out (yeah, right). So, while I could use LINQ to convert my DataSets to IQueryable, I would like to have a generic solution so I don't have to write a custom query for each class. I'm tinkering with reflection right now, but in the meantime I have two questions: Are there any problems I overlooked with this solution? Are there any other approaches you would recommend to convert DataSets to POCOs? Thanks in advance.

    Read the article

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