Search Results

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

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

  • ASP.Net Entity Framework Repository & Linq

    - by Chris Klepeis
    My scenario: This is an ASP.NET 4.0 web app programmed via C# I implement a repository pattern. My repositorys all share the same ObjectContext, which is stored in httpContext.Items. Each repository creates a new ObjectSet of type E. Heres some code from my repository: public class Repository<E> : IRepository<E>, IDisposable where E : class { private DataModelContainer _context = ContextHelper<DataModelContainer>.GetCurrentContext(); private IObjectSet<E> _objectSet; private IObjectSet<E> objectSet { get { if (_objectSet == null) { _objectSet = this._context.CreateObjectSet<E>(); } return _objectSet; } } public IQueryable<E> GetQuery() { return objectSet; } Lets say I have 2 repositorys, 1 for states and 1 for countrys and want to create a linq query against both. Note that I use POCO classes with the entity framework. State and Country are 2 of these POCO classes. Repository stateRepo = new Repository<State>(); Repository countryRepo = new Repository<Country>(); IEnumerable<State> states = (from s in _stateRepo.GetQuery() join c in _countryRepo.GetQuery() on s.countryID equals c.countryID select s).ToList(); Debug.WriteLine(states.First().Country.country) essentially, I want to retrieve the state and the related country entity. The query only returns the state data... and I get a null argument exception on the Debug.WriteLine LazyLoading is disabled in my .edmx... thats the way I want it.

    Read the article

  • Membership.GetUser() within TransactionScope throws TransactionPromotionException

    - by Bob Kaufman
    The following code throws a TransactionAbortedException with message "The transaction has aborted" and an inner TransactionPromotionException with message "Failure while attempting to promote transaction": using ( TransactionScope transactionScope = new TransactionScope() ) { try { using ( MyDataContext context = new MyDataContext() ) { Guid accountID = new Guid( Request.QueryString[ "aid" ] ); Account account = ( from a in context.Accounts where a.UniqueID.Equals( accountID ) select a ).SingleOrDefault(); IQueryable < My_Data_Access_Layer.Login > loginList = from l in context.Logins where l.AccountID == account.AccountID select l; foreach ( My_Data_Access_Layer.Login login in loginList ) { MembershipUser membershipUser = Membership.GetUser( login.UniqueID ); } [... lots of DeleteAllOnSubmit() calls] context.SubmitChanges(); transactionScope.Complete(); } } catch ( Exception E ) { [... reports the exception ...] } } The error occurs at the call to Membership.GetUser(). My Connection String is: <add name="MyConnectionString" connectionString="Data Source=localhost\SQLEXPRESS;Initial Catalog=MyDatabase;Integrated Security=True" providerName="System.Data.SqlClient" /> Everything I've read tells me that TransactionScope should just get magically applied to the Membership calls. The user exists (I'd expect a null return otherwise.)

    Read the article

  • ASP.NET MVC pagination problem????

    - by MD_Oppenheimer
    OK, This is starting to get mildly irritating. I tried to implement Twitter style paging using ASP.NET MVC and JQuery my problem is that when not using Request.IsAjaxRequest() (for users with javascript turned off) it works fine, obviously posting back the whole page. when I run the code for Request.IsAjaxRequest(), it skips entries, and does not return result in order. this is the code I have: public ActionResult Index(int? startRow) { StatusUpdatesRepository statusUpdatesRepository = new StatusUpdatesRepository(); if (!startRow.HasValue) startRow = Globals.Settings.StatusUpdatesSection.StatusUpdateCount;//5 Default starting row //Retrieve the first page with a page size of entryCount int totalItems; if (Request.IsAjaxRequest()) { IEnumerable<StatusUpdate> PagedEntries = statusUpdatesRepository.GetLastStatusUpdates(startRow.Value,Globals.Settings.StatusUpdatesSection.StatusUpdateCount, out totalItems); if (startRow < totalItems) AddMoreUrlToViewData(startRow.Value); return View("StatusUpdates", PagedEntries); } //Retrieve the first page with a page size of global setting // First run skip 0 take 5 IEnumerable<StatusUpdate> entries = statusUpdatesRepository.GetLastStatusUpdates(0,startRow.Value, out totalItems); if (startRow < totalItems) AddMoreUrlToViewData(startRow.Value); return View(entries); } private void AddMoreUrlToViewData(int entryCount) { ViewData["moreUrl"] = Url.Action("Index", "Home", new { startRow = entryCount + Globals.Settings.StatusUpdatesSection.StatusUpdateCount }); } My GetLastStatusUpdates function: public IQueryable GetLastStatusUpdates(int startRowIndex, int maximumRows,out int statusUpdatesCount ) { statusUpdatesCount = db.StatusUpdates.Count(); return db.StatusUpdates .Skip(startRowIndex) .Take(maximumRows) .OrderByDescending(s = s.AddedDate); } Really fresh out out of ideas as to why this is not working properly when responding to a Request.IsAjaxRequest(), ie when I turn of javascript in the browser, the code works perfectly, except I don't want to repost the whole page????

    Read the article

  • Help Converting T-SQL Query to LINQ Query

    - by campbelt
    I am new to LINQ, and so am struggle over some queries that I'm sure are pretty simple. In any case, I have been hiting my head against this for a while, but I'm stumped. Can anyone here help me convert this T-SQL query into a LINQ query? Once I see how it is done, I'm sure I'll have some question about the syntax: SELECT BlogTitle FROM Blogs b JOIN BlogComments bc ON b.BlogID = bc.BlogID WHERE b.Deleted = 0 AND b.Draft = 0 AND b.[Default] = 0 AND bc.Deleted = 0 GROUP BY BlogTitle ORDER BY MAX([bc].[Timestamp]) DESC Just to show that I have tried to solve this on my own, here is what I've come up with so far, though it doesn't compile, let alone work ... var iqueryable = from blog in db.Blogs join blogComment in db.BlogComments on blog.BlogID equals blogComment.BlogID where blog.Deleted == false && blog.Draft == false && blog.Default == false && blogComment.Deleted == false group blogComment by blog.BlogID into blogGroup orderby blogGroup.Max(blogComment => blogComment.Timestamp) select blogGroup;

    Read the article

  • Settings variable values in a Moq Callback() call

    - by Adam Driscoll
    I think I may be a bit confused on the syntax of the Moq Callback methods. When I try to do something like this: IFilter filter = new Filter(); List<IFoo> objects = new List<IFoo> { new Foo(), new Foo() }; IQueryable myFilteredFoos = null; mockObject.Setup(m => m.GetByFilter(It.IsAny<IFilter>())).Callback( (IFilter filter) => myFilteredFoos = filter.FilterCollection(objects)).Returns(myFilteredFoos.Cast<IFooBar>()); This throws a exception because myFilteredFoos is null during the Cast<IFooBar>() call. Is this not working as I expect? I would think FilterCollection would be called and then myFilteredFoos would be non-null and allow for the cast. FilterCollection is not capable of returning a null which draws me to the conclusion it is not being called. Also, when I declare myFilteredFoos like this: Queryable myFilteredFoos; The Return call complains that myFilteredFoos may be used before it is initialized.

    Read the article

  • Create System.Data.Linq.Table in Code for Testing

    - by S. DePouw
    I have an adapter class for Linq-to-Sql: public interface IAdapter : IDisposable { Table<Data.User> Activities { get; } } Data.User is an object defined by Linq-to-Sql pointing to the User table in persistence. The implementation for this is as follows: public class Adapter : IAdapter { private readonly SecretDataContext _context = new SecretDataContext(); public void Dispose() { _context.Dispose(); } public Table<Data.User> Users { get { return _context.Users; } } } This makes mocking the persistence layer easy in unit testing, as I can just return whatever collection of data I want for Users (Rhino.Mocks): Expect.Call(_adapter.Users).Return(users); The problem is that I cannot create the object 'users' since the constructors are not accessible and the class Table is sealed. One option I tried is to just make IAdapter return IEnumerable or IQueryable, but the problem there is that I then do not have access to the methods ITable provides (e.g. InsertOnSubmit()). Is there a way I can create the fake Table in the unit test scenario so that I may be a happy TDD developer?

    Read the article

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

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

    Read the article

  • How do you cast a LinqToSql Table<TEntity> as a Table<IEntity> where TEntity : IEntity?

    - by DanM
    I'm trying to use DbLinq with a SQLite database, but I'm running into a problem when I try to cast an ITable as a Queryable<TEntity>. There is a known bug in DbLinq (Issue 211), which might be the source of my problem, but I wanted to make sure my code is sound and, if it is, find out if there might be something I can do to work around the bug. Here is the generic repository method that attempts to do the cast: public IQueryable<TEntity> GetAll() { return Table.Cast<TEntity>(); // Table is an ITable } This compiles, but if I pass in the interface IPerson for TEntity and the type of the entities in the table is Person (where Person : IPerson), I'm getting this error from DbLinq: S0133: Implement QueryMethod Queryable.Cast. Why am I trying to do this? I have a library project that doesn't know the type of the entity until runtime, but it does know the interface for the entity. So, I'm trying to cast to the interface type so that my library project can consume the data. Questions: Am I attempting an impossible cast or is this definitely a bug in DbLinq? How else could I go about solving my problem?

    Read the article

  • asp.net mvc json result format

    - by ile
    public class JsonCategoriesDisplay { public JsonCategoriesDisplay() { } public int CategoryID { set; get; } public string CategoryTitle { set; get; } } public class ArticleCategoryRepository { private DB db = new DB(); public IQueryable<JsonCategoriesDisplay> JsonFindAllCategories() { var result = from c in db.ArticleCategories select new JsonCategoriesDisplay { CategoryID = c.CategoryID, CategoryTitle = c.Title }; return result; } .... } public class ArticleController : Controller { ArticleRepository articleRepository = new ArticleRepository(); ArticleCategoryRepository articleCategoryRepository = new ArticleCategoryRepository(); public string Categories() { var jsonCats = articleCategoryRepository.JsonFindAllCategories().ToList(); //return Json(jsonCats, JsonRequestBehavior.AllowGet); return new JavaScriptSerializer().Serialize(new { jsonCats}); } } This results with following: {"jsonCats":[{"CategoryID":2,"CategoryTitle":"Politika"},{"CategoryID":3,"CategoryTitle":"Informatika"},{"CategoryID":4,"CategoryTitle":"Nova kategorija"},{"CategoryID":5,"CategoryTitle":"Testna kategorija"}]} If I use line that is commented and place JsonResult instead of returning string, I get following result: [{"CategoryID":2,"CategoryTitle":"Politika"},{"CategoryID":3,"CategoryTitle":"Informatika"},{"CategoryID":4,"CategoryTitle":"Nova kategorija"},{"CategoryID":5,"CategoryTitle":"Testna kategorija"}] But, I need result to be formatted like this: {'2':'Politika','3':'Informatika','4':'Nova kateorija','5':'Testna kategorija'} Is there a simple way to accomplish this or I will need to hardcode result? Thanks in advance!

    Read the article

  • MVC and repository pattern data effeciency

    - by Shawn Mclean
    My project is structured as follows: DAL public IQueryable<Post> GetPosts() { var posts = from p in context.Post select p; return posts; } Service public IList<Post> GetPosts() { var posts = repository.GetPosts().ToList(); return posts; } //Returns a list of the latest feeds, restricted by the count. public IList<PostFeed> GetPostFeeds(int latestCount) { List<Post> post - GetPosts(); //CODE TO CREATE FEEDS HERE return feeds; } Lets say the GetPostFeeds(5) is supposed to return the 5 latest feeds. By going up the list, doesn't it pull down every single post from the database from GetPosts(), just to extract 5 from it? If each post is say 5kb from the database, and there is 1 million records. Wont that be 5GB of ram being used per call to GetPostFeeds()? Is this the way it happens? Should I go back to my DAL and write queries that return only what I need?

    Read the article

  • LINQ compiled query DataBind issue

    - by Brian
    Hello All, I have a pretty extensive reporting page that uses LINQ. There is one main function that returns an IQueryable object. I then further filter / aggregate the returned query depending on the report the user needs. I changed this function to a compiled query, it worked great, and the speed increase was astonishing. The only problem comes when i want to databind the results. I am databinding to a standard asp.net GridView and it works fine, no problems. I am also databinding to an asp.net chart control, this is where my page is throwing an error. this works well: GridView gv = new GridView(); gv.DataSource = gridSource; But this does not: Series s1 = new Series("Series One"); s1.Points.DataBindXY(gridSource, "Month", gridSource, "Success"); The error i receive is this: System.NotSupportedException Specified method is not supported When i look into my gridSource var at run time i see this using a typical linq query: SELECT [t33].[value2] AS [Year], [t33].[value22] AS [Month], [t33].[value3] AS [Calls]...... I see this after i change the query to compiled: {System.Linq.OrderedEnumerable<<>f__AnonymousType15<string,int,int,int,int,int,int,int>,string>} This is obviously the reason why the databindxy is no longer working, but i am not sure how to get around it. Any help would be appreciated! Thanks

    Read the article

  • How can i Write list type returning value in Linq with Entity FrameWork?

    - by programmerist
    How can i return List<personel> data type from below procedure. if i press F5 it throw me this error: Error 1 Cannot implicitly convert type 'System.Linq.IQueryable' to 'System.Collections.Generic.List'. An explicit conversion exists (are you missing a cast?) C:\Documents and Settings\yusufk\Desktop\EFTestSolutions\WebApplicationTest1\WebApplicationTest1\Default.aspx.cs 101 61 WebApplicationTest1 i think that: i should rearrange or recode "select new {. . . . " ? protected List<personel> GetPersonalsData2() { List<personel> personeller; using (FirmaEntities firmactx = new FirmaEntities()) { personeller = (from p in firmactx.Personals select new { p.ID, p.Name, p.SurName }); return personeller.ToList(); } } } public class personel { public int ID { get; set; } public string Name { get; set; } public string SurName { get; set; } }

    Read the article

  • MVC and repository pattern data efficiency

    - by Shawn Mclean
    My project is structured as follows: DAL public IQueryable<Post> GetPosts() { var posts = from p in context.Post select p; return posts; } Service public IList<Post> GetPosts() { var posts = repository.GetPosts().ToList(); return posts; } //Returns a list of the latest feeds, restricted by the count. public IList<PostFeed> GetPostFeeds(int latestCount) { List<Post> post - GetPosts(); //CODE TO CREATE FEEDS HERE return feeds; } Lets say the GetPostFeeds(5) is supposed to return the 5 latest feeds. By going up the list, doesn't it pull down every single post from the database from GetPosts(), just to extract 5 from it? If each post is say 5kb from the database, and there is 1 million records. Wont that be 5GB of ram being used per call to GetPostFeeds()? Is this the way it happens? Should I go back to my DAL and write queries that return only what I need?

    Read the article

  • Passing a LINQ DataRow Reference in a GridView's ItemTemplate

    - by Bob Kaufman
    Given the following GridView: <asp:GridView runat="server" ID="GridView1" AutoGenerateColumns="false" DataKeyNames="UniqueID" OnSelectedIndexChanging="GridView1_SelectedIndexChanging" > <Columns> <asp:BoundField HeaderText="Remarks" DataField="Remarks" /> <asp:TemplateField HeaderText="Listing"> <ItemTemplate> <%# ShowListingTitle( ( ( System.Data.DataRowView ) ( Container.DataItem ) ).Row ) %> </ItemTemplate> </asp:TemplateField> <asp:BoundField HeaderText="Amount" DataField="Amount" DataFormatString="{0:C}" /> </Columns> </asp:GridView> which refers to the following code-behind method: protected String ShowListingTitle( DataRow row ) { Listing listing = ( Listing ) row; return NicelyFormattedString( listing.field1, listing.field2, ... ); } The cast from DataRow to Listing is failing (cannot convert from DataRow to Listing) I'm certain the problem lies in what I'm passing from within the ItemTemplate, which is simply not the right reference to the current record from the LINQ to SQL data set that I've created, which looks like this: private void PopulateGrid() { using ( MyDataContext context = new MyDataContext() ) { IQueryable < Listing > listings = from l in context.Listings where l.AccountID == myAccountID select l; GridView1.DataSource = listings; GridView1.DataBind(); } }

    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 Datacontext Disposal Issues

    - by Refracted Paladin
    I am getting a Cannot access object: DataContext after it's been disposed in the below DAL method. I thought that I would be okay calling dispose there. result is an IEnumurable and I thought it was IQueryable that caused these kinds of problems. What am I doing wrong? How SHOULD I be disposing of my DataContext. Is there something better to be returning then a DataTable? This is a Desktop app that points at SQL 2005. Example method that causes this error -- public static DataTable GetEnrolledMembers(Guid workerID) { var DB = CmoDataContext.Create(); var AllEnrollees = from enrollment in DB.tblCMOEnrollments where enrollment.CMOSocialWorkerID == workerID || enrollment.CMONurseID == workerID join supportWorker in DB.tblSupportWorkers on enrollment.EconomicSupportWorkerID equals supportWorker.SupportWorkerID into workerGroup from worker in workerGroup.DefaultIfEmpty() select new { enrollment.ClientID, enrollment.CMONurseID, enrollment.CMOSocialWorkerID, enrollment.EnrollmentDate, enrollment.DisenrollmentDate, ESFirstName = worker.FirstName, ESLastName = worker.LastName, ESPhone = worker.Phone }; var result = from enrollee in AllEnrollees.AsEnumerable() where (enrollee.DisenrollmentDate == null || enrollee.DisenrollmentDate > DateTime.Now) //let memberName = BLLConnect.MemberName(enrollee.ClientID) let lastName = BLLConnect.MemberLastName(enrollee.ClientID) let firstName = BLLConnect.MemberFirstName(enrollee.ClientID) orderby enrollee.DisenrollmentDate ascending, lastName ascending select new { enrollee.ClientID, //MemberName = memberName, LastName = lastName, FirstName = firstName, NurseName = BLLAspnetdb.NurseName(enrollee.CMONurseID), SocialWorkerName = BLLAspnetdb.SocialWorkerName(enrollee.CMOSocialWorkerID), enrollee.EnrollmentDate, enrollee.DisenrollmentDate, ESWorkerName = enrollee.ESFirstName + " " + enrollee.ESLastName, enrollee.ESPhone }; DB.Dispose(); return result.CopyLinqToDataTable(); } partial class where I create the DataContext -- partial class CmoDataContext { public static bool IsDisconnectedUser { get { return Settings.Default.IsDisconnectedUser; } } public static CmoDataContext Create() { var cs = IsDisconnectedUser ? Settings.Default.CMOConnectionString : Settings.Default.Central_CMOConnectionString; return new CmoDataContext(cs); }

    Read the article

  • System.AccessViolationException when using TPT inheritance in Entity Framework CTP5

    - by Ben
    Hi, I'm using TPT inheritance in EF CTP5 with SQL CE 4. I have an abstract base class "Widget" with common properties like "Title". I can successfully save concrete Widget implementations e.g. "TwitterWidget". However, I have a problem retrieving all widgets (or rather ALL widget implementations). My repository exposes the following: public IQueryable<Widget> GetAll(); This effectively returns the IDbSet from the DbContext. The following queries work fine: repo.GetAll().ToList(); repo.GetAll().Where(w => w.Title == "Test").ToList(); repo.GetAll().SingleOrDefault(w => w.Title == "Test"); repo.GetAll().Where(w => w.Title == "Test").OrderBy(x => x.Title).ToList(); However, if I write the following query: repo.GetAll().OrderBy(w => w.Title); I get the following error: Test 'PlanetCloud.Portfolio.Tests.Data.PersistenceTestFixture.Can_get_widgets' failed: System.AccessViolationException : Attempted to read or write protected memory. This is often an indication that other memory is corrupt. at System.Data.SqlServerCe.NativeMethodsHelper.GetValues(IntPtr pSeCursor, Int32 seGetColumn, IntPtr prgBinding, Int32 cDbBinding, IntPtr pData, IntPtr pError) at System.Data.SqlServerCe.NativeMethods.GetValues(IntPtr pSeCursor, Int32 seGetColumn, IntPtr prgBinding, Int32 cDbBinding, IntPtr pData, IntPtr pError) at System.Data.SqlServerCe.SqlCeDataReader.FetchValue(Int32 index) at System.Data.SqlServerCe.SqlCeDataReader.IsDBNull(Int32 ordinal) at lambda_method(Closure , Shaper ) at System.Data.Common.Internal.Materialization.Shaper.HandleEntityAppendOnly[TEntity](Func`2 constructEntityDelegate, EntityKey entityKey, EntitySet entitySet) at lambda_method(Closure , Shaper ) at System.Data.Common.Internal.Materialization.Coordinator`1.ReadNextElement(Shaper shaper) at System.Data.Common.Internal.Materialization.Shaper`1.SimpleEnumerator.MoveNext() at System.Collections.Generic.List`1..ctor(IEnumerable`1 collection) at System.Linq.Enumerable.ToList[TSource](IEnumerable`1 source) However, I can execute the following query without problems: var widgets = repo.GetAll().OfType<Widget>().OrderBy(w => w.Title).ToList(); So if I specify the type as the base class prior to my orderby clause it works. The question is why?

    Read the article

  • Linq: the linked objects are null, why?

    - by user46503
    Hello, I have several linked tables (entities). I'm trying to get the entities using the following linq: ObjectQuery<Location> locations = context.Location; ObjectQuery<ProductPrice> productPrice = context.ProductPrice; ObjectQuery<Product> products = context.Product; IQueryable<ProductPrice> res1 = from pp in productPrice join loc in locations on pp.Location equals loc join prod in products on pp.Product equals prod where prod.Title.ToLower().IndexOf(Word.ToLower()) > -1 select pp; This query returns 2 records, ProductPrice objects that have linked object Location and Product but they are null and I cannot understand why. If I try to fill them in the linq as below: res = from pp in productPrice join loc in locations on pp.Location equals loc join prod in products on pp.Product equals prod where prod.Title.ToLower().IndexOf(Word.ToLower()) > -1 select new ProductPrice { ProductPriceId = pp.ProductPriceId, Product = prod }; I have the exception "The entity or complex type 'PBExplorerData.ProductPrice' cannot be constructed in a LINQ to Entities query" Could someone please explain me what happens and what I need to do? Thanks

    Read the article

  • Entity framework entity class mapping with plain .net class

    - by Elan
    I have following in entity framework Table - Country Fields List item Country_ID Dialing_Code ISO_Alpha2 ISO_Alpha3 ISO_Full I would like to map only selected fields from this entity model to my domain class. My domain model class is public class DomainCountry { public int Country_ID { get; set; } public string Dialing_Code { get; set; } public string ISO_3166_1_Alpha_2 { get; set; } } The following will work however insert or update is not possible. In order to get insert or update we need to use ObjectSet< but it will not support in my case. IQueryable<DomainCountry> countries = context.Countries.Select( c => new DomainCountry { Country_ID = c.Country_Id, Dialing_Code = c.Dialing_Code, ISO_3166_1_Alpha_2 = c.ISO_3166_1_Alpha_2 }); It will be really fantastic could someone provide a nice solution for this. Ideally it will be kind of proxy class which will support all the futures however highly customizable i.e. only the columns we want to expose to the outer world

    Read the article

  • Trouble with LINQ databind to GridView and RowDataBound

    - by Michael
    Greetings all, I am working on redesigning my personal Web site using VS 2008 and have chosen to use LINQ to create by data-access layer. Part of my site will be a little app to help manage my budget better. My first LINQ query does successfully execute and display in a GridView, but when I try to use a RowDataBound event to work with the results and refine them a bit, I get the error: The type or namespace name 'var' could not be found (are you missing a using directive or an assembly reference?) This interesting part is, if I just try to put in a var s = "s"; anywhere else in the same file, I get the same error too. If I go to other files in the web project, var s = "s"; compiles fine. Here is the LINQ Query call: public static IQueryable pubGetRecentTransactions(int param_accountid) { clsDataContext db; db = new clsDataContext(); var query = from d in db.tblMoneyTransactions join p in db.tblMoneyTransactions on d.iParentTransID equals p.iTransID into dp from p in dp.DefaultIfEmpty() where d.iAccountID == param_accountid orderby d.dtTransDate descending, d.iTransID ascending select new { d.iTransID, d.dtTransDate, sTransDesc = p != null ? p.sTransDesc : d.sTransDesc, d.sTransMemo, d.mTransAmt, d.iCheckNum, d.iParentTransID, d.iReconciled, d.bIsTransfer }; return query; } protected void Page_Load(object sender, EventArgs e) { if (!this.IsPostBack) { this.prvLoadData(); } } internal void prvLoadData() { prvCtlGridTransactions.DataSource = clsMoneyTransactions.pubGetRecentTransactions(2); prvCtlGridTransactions.DataBind(); } protected void prvCtlGridTransactions_RowDataBound(object sender, GridViewRowEventArgs e) { if (e.Row.RowType == DataControlRowType.DataRow) { var datarow = e.Row.DataItem; var s = "s"; e.Row.Cells[0].Text = datarow.dtTransDate.ToShortDateString(); e.Row.Cells[1].Text = datarow.sTransDesc; e.Row.Cells[2].Text = datarow.mTransAmt.ToString("c"); e.Row.Cells[3].Text = datarow.iReconciled.ToString(); }//end if }//end RowDataBound My googling to date hasn't found a good answer, so I turn it over to this trusted community. I appreciate your time in assisting me.

    Read the article

  • linq-to-sql combine child expressions

    - by VictorS
    I need to create and combine several expressions for child entity into one to use it on "Any" operator of a parent. Code now looks like this: Expresion<Child, bool> startDateExpression = t => t.start_date >= startDate; Expression<Child, bool> endDateExpression = t => t.end_date <= endDate; .... ParameterExpression param = startDateExpression.Parameters[0]; Expression<Func<T, bool>> Combined = Expression.Lambda<Func<Child, bool>>( Expression.AndAlso(startDateExpression.Body, startDateExpression.Body), param); //but now I am trying to use combined expression on parent //this line fails just to give an idea on what I am trying to do: //filter type is IQueryable<Parent>; var filter = filter.Where(p =>p.Children.Any(Combined)); How can I do that? Is there better(more elegant way way of doing it?

    Read the article

  • Multi-tenant Access Control: Repository or Service layer?

    - by FreshCode
    In a multi-tenant ASP.NET MVC application based on Rob Conery's MVC Storefront, should I be filtering the tenant's data in the repository or the service layer? 1. Filter tenant's data in the repository: public interface IJobRepository { IQueryable<Job> GetJobs(short tenantId); } 2. Let the service filter the repository data by tenant: public interface IJobService { IList<Job> GetJobs(short tenantId); } My gut-feeling says to do it in the service layer (option 2), but it could be argued that each tenant should in essence have their own "virtual repository," (option 1) where this responsibility lies with the repository. Which is the most elegant approach: option 1, option 2 or is there a better way? Update: I tried the proposed idea of filtering at the repository, but the problem is that my application provides the tenant context (via sub-domain) and only interacts with the service layer. Passing the context all the way to the repository layer is a mission. So instead I have opted to filter my data at the service layer. I feel that the repository should represent all data physically available in the repository with appropriate filters for retrieving tenant-specific data, to be used by the service layer. Final Update: I ended up abandoning this approach due to the unnecessary complexities. See my answer below.

    Read the article

  • Expression Tree with Property Inheritance causes an argument exception

    - by Adam Driscoll
    Following this post: link text I'm trying to create an expression tree that references the property of a property. My code looks like this: public interface IFoo { void X {get;set;} } public interface IBar : IFoo { void Y {get;set;} } public interface IFooBarContainer { IBar Bar {get;set;} } public class Filterer { //Where T = "IFooBarContainer" public IQueryable<T> Filter<T>(IEnumerable<T> collection) { var argument = Expression.Parameter(typeof (T), "item"); //... //where propertyName = "IBar.X"; PropertyOfProperty(argument, propertyName); } private static MemberExpression PropertyOfProperty(Expression expr, string propertyName) { return propertyName.Split('.').Aggregate<string, MemberExpression>(null, (current, property) => Expression.Property(current ?? expr, property)); } } I receive the exception: System.ArgumentException: Instance property 'X' is not defined for type 'IBar' ReSharper turned the code in the link above into the condensed statement in my example. Both forms of the method returned the same error. If I reference IBar.Y the method does not fail.

    Read the article

  • Retrive data from two tables in asp.net mvc using ADO.Net Entity Framework

    - by user192972
    Please read my question carefully and reply me. I have two tables as table1 and table2. In table1 i have columns as AddressID(Primary Key),Address1,Address2,City In table2 i have columns as ContactID(Primary Key),AddressID(Foriegn Key),Last Name,First Name. By using join operation i can retrive data from both the tables. I created a Model in my MVC Application.I can see both the tables in enitity editor. In the ViewData folder of my solution explorer i created two class as ContactViewData.cs and SLXRepository.cs In the ContactViewData.cs i have following code public IEnumerable<CONTACT> contacts { get; set; } In the SLXRepository.cs i have following code public IEnumerable<CONTACT> GetContacts() { var contact = ( from c in context.CONTACT join a in context.ADDRESS on c.ADDRESSID equals a.ADDRESSID select new { a.ADDRESS1, a.ADDRESS2, a.CITY, c.FIRSTNAME, c.LASTNAME } ); return contact; } I am getting the error in return type Cannot implicitly convert type 'System.Linq.IQueryable' to 'System.Collections.Generic.IEnumerable'. An explicit conversion exists (are you missing a cast?)

    Read the article

  • what does this asp.net mvc compile time error states?

    - by Pandiya Chendur
    I have a repository class and it has this, using System; using System.Collections.Generic; using System.Linq; using System.Web; using System.Web.Mvc; using CrMVC.BusinessObjects; namespace CrMVC.Models { public class ConstructionRepository { private CRDataContext db = new CRDataContext(); public IQueryable<MaterialsObj> FindAllMaterials() { var materials = from m in db.Materials join Mt in db.MeasurementTypes on m.MeasurementTypeId equals Mt.Id select new MaterialsObj() { Id = Convert.ToInt64(m.Mat_id), Mat_Name = m.Mat_Name, Mes_Name = Mt.Name, }; return materials; } } } And My MaterialsObj class is under CrMVC.BusinessObjects namespace and i using it in my repository class.... namespace CrMVC.BusinessObjects { public class MaterialsObj { //My logic here } } But when i compile this i get this error c:\WINDOWS\Microsoft.NET\Framework\v2.0.50727\Temporary ASP.NET Files\root\19360d4c\3d21e226\App_Web_materials.aspx.7d2669f4.a8f-zsw5.0.cs(148): error CS0426: The type name 'Materials' does not exist in the type 'CrMVC.Models.ConstructionRepository' Am i missing something any suggestion.... Edit: There is no class named Materials in my repository class then why i get this error..

    Read the article

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