Search Results

Search found 720 results on 29 pages for 'tolist'.

Page 22/29 | < Previous Page | 18 19 20 21 22 23 24 25 26 27 28 29  | Next Page >

  • ASP.NET MVC - How to Unit Test boundaries in the Repository pattern?

    - by JK
    Given a basic repository interface: public interface IPersonRepository { void AddPerson(Person person); List<Person> GetAllPeople(); } With a basic implementation: public class PersonRepository: IPersonRepository { public void AddPerson(Person person) { ObjectContext.AddObject(person); } public List<Person> GetAllPeople() { return ObjectSet.AsQueryable().ToList(); } } How can you unit test this in a meaningful way? Since it crosses the boundary and physically updates and reads from the database, thats not a unit test, its an integration test. Or is it wrong to want to unit test this in the first place? Should I only have integration tests on the repository? I've been googling the subject and blogs often say to make a stub that implements the IRepository: public class PersonRepositoryTestStub: IPersonRepository { private List<Person> people = new List<Person>(); public void AddPerson(Person person) { people.Add(person); } public List<Person> GetAllPeople() { return people; } } But that doesnt unit test PersonRepository, it tests the implementation of PersonRepositoryTestStub (not very helpful).

    Read the article

  • Big problem with fluent nhibernate, c# and MySQL need to search in BLOB

    - by VinnyG
    I've done a big mistake, now I have to find a solution. It was my first project working with fluent nhibernate, I mapped an object this way : public PosteCandidateMap() { Id(x => x.Id); Map(x => x.Candidate); Map(x => x.Status); Map(x => x.Poste); Map(x => x.MatchPossibility); Map(x => x.ModificationDate); } So the whole Poste object is in the database but I would have need only the PosteId. Now I got to find all Candidates for one Poste so when I look in my repository I have : return GetAll().Where(x => x.Poste.Id == id).ToList(); But this is very slow since it loads all the items, we now have more than 1500 items in the table, at first to project was not supposed to be that big (not a big paycheck either). Now I'm trying to do this with criterion ou Linq but it's not working since my Poste is in a BLOB. Is there anyway I can change this easyly? Thanks a lot for the help!

    Read the article

  • How to flatten list of options using higher order functions?

    - by Synesso
    Using Scala 2.7.7: If I have a list of Options, I can flatten them using a for-comprehension: val listOfOptions = List(None, Some("hi"), None) listOfOptions: List[Option[java.lang.String]] = List(None, Some(hi), None) scala> for (opt <- listOfOptions; string <- opt) yield string res0: List[java.lang.String] = List(hi) I don't like this style, and would rather use a HOF. This attempt is too verbose to be acceptable: scala> listOfOptions.flatMap(opt => if (opt.isDefined) Some(opt.get) else None) res1: List[java.lang.String] = List(hi) Intuitively I would have expected the following to work, but it doesn't: scala> List.flatten(listOfOptions) <console>:6: error: type mismatch; found : List[Option[java.lang.String]] required: List[List[?]] List.flatten(listOfOptions) Even the following seems like it should work, but doesn't: scala> listOfOptions.flatMap(_: Option[String]) <console>:6: error: type mismatch; found : Option[String] required: (Option[java.lang.String]) => Iterable[?] listOfOptions.flatMap(_: Option[String]) ^ The best I can come up with is: scala> listOfOptions.flatMap(_.toList) res2: List[java.lang.String] = List(hi) ... but I would much rather not have to convert the option to a list. That seems clunky. Any advice?

    Read the article

  • F# - POCO Class

    - by ebb
    Hey there! I'm trying to write a POCO class in proper F#... But something is wrong.. The C# code that I want to "translate" to proper F# is: public class MyTest { [Key] public int ID { get; set; } public string Name { get; set; } } The closest I can come to the above code in F# is something like: type Mytest() = let mutable _id : int = 0; let mutable _name : string = null; [<KeyAttribute>] member x.ID with public get() : int = _id and public set(value) = _id <- value member x.Name with public get() : string = _name and public set value = _name <- value However when I try to access the properties of the F# version it just returns a compile error saying "Lookup on object of indeterminate type based on information prior to this program point. A type annotation may be needed prior to this program point to constrain the type of the object. This may allow the lookup to be resolved." The code thats trying to get the property is a part of my Repository (I'm using EF Code First). module Databasethings = let GetEntries = let ctx = new SevenContext() let mydbset = ctx.Set<MyTest>() let entries = mydbset.Select(fun item -> item.Name).ToList() // This line comes up with a compile error at "item.Name" (the compile error is written above) entries What the hell is going on? Thanks in advance!

    Read the article

  • Entity Framework + MySQL - Why is the performance so terrible?

    - by Cyril Gupta
    When I decided to use an OR/M (Entity Framework for MySQL this time) for my new project I was hoping it would save me time, but I seem to have failed it (for the second time now). Take this simple SQL Query SELECT * FROM POST ORDER BY addedOn DESC LIMIT 0, 50 It executes and gives me results in less than a second as it should (the table has about 60,000 rows). Here's the equivalent LINQ To Entities query that I wrote for this var q = (from p in db.post orderby p.addedOn descending select p).Take(50); var q1 = q.ToList(); //This is where the query is fetched and timed out But this query never even executes it times out ALWAYS (without orderby it takes 5 seconds to run)! My timeout is set to 12 seconds so you can imagine it is taking much more than that. Why is this happening? Is there a way I can see what is the actual SQL Query that Entity Framework is sending to the db? Should I give up on EF+MySQL and move to standard SQL before I lose all eternity trying to make it work? I've recalibrated my indexes, tried eager loading (which actually makes it fail even without the orderby clause) Please help, I am about to give up OR/M for MySQL as a lost cause.

    Read the article

  • Azure batch operations delete several blobs and tables

    - by reft
    I have a function that deletes every table & blob that belongs to the affected user. CloudTable uploadTable = CloudStorageServices.GetCloudUploadsTable(); TableQuery<UploadEntity> uploadQuery = uploadTable.CreateQuery<UploadEntity>(); List<UploadEntity> uploadEntity = (from e in uploadTable.ExecuteQuery(uploadQuery) where e.PartitionKey == "uploads" && e.UserName == User.Idendity.Name select e).ToList(); foreach (UploadEntity uploadTableItem in uploadEntity) { //Delete table TableOperation retrieveOperationUploads = TableOperation.Retrieve<UploadEntity>("uploads", uploadTableItem.RowKey); TableResult retrievedResultUploads = uploadTable.Execute(retrieveOperationUploads); UploadEntity deleteEntityUploads = (UploadEntity)retrievedResultUploads.Result; TableOperation deleteOperationUploads = TableOperation.Delete(deleteEntityUploads); uploadTable.Execute(deleteOperationUploads); //Delete blob CloudBlobContainer blobContainer = CloudStorageServices.GetCloudBlobsContainer(); CloudBlockBlob blob = blobContainer.GetBlockBlobReference(uploadTableItem.BlobName); blob.Delete(); } Each table got its own blob, so if the list contains 3 uploadentities, the 3 table and the 3 blobs will be deleted. I heard you can use table batch operations for reduce cost and load. I tried it, but failed miserable. Anyone intrested in helping me:)? Im guessing tablebatch operations are for tables only, so its a no go for blobs, right? How would you add tablebatchoperations for this code? Do you see any other improvements that can be done? Thanks!

    Read the article

  • LINQ to Entites - Left Outer Join - SQL 2000

    - by user255234
    Hi! I'm using Linq to Entities. I have the following query in my code, it includes left outer Join: var surgeonList = (from item in context.T1_STM_Surgeon.Include("T1_STM_SurgeonTitle") .Include("OTER").Include("OSLP") join reptable in context.OSLP on item.Rep equals reptable.SlpCode into surgRepresentative where item.ID == surgeonId select new { ID = item.ID, First = item.First, Last = item.Last, Rep = (surgRepresentative.FirstOrDefault() != null) ? surgRepresentative.FirstOrDefault().SlpName : "N/A", Reg = item.OTER.descript, PrimClinic = item.T1_STM_ClinicalCenter.Name, Titles = item.T1_STM_SurgeonTitle, Phone = item.Phone, Email = item.Email, Address1 = item.Address1, Address2 = item.Address2, City = item.City, State = item.State, Zip = item.Zip, Comments = item.Comments, Active = item.Active, DateEntered = item.DateEntered }) .ToList(); My DEV server has SQL 2008, so the code works just fine. When I moved this code to client's production server - they use SQL 2000, I started getting "Incorrect syntax near '(' ". I've tried changing the ProviderManifestToken to 2000 in my .edmx file, then I started getting "The execution of this query requires the APPLY operator, which is not supported in versions of SQL Server earlier than SQL Server 2005." I tied changing the token to 2005, the "Incorrect syntax near '(' " is back. Can anybody help me to find a workaround for this? Thank you very much in advance!

    Read the article

  • wpf treeview does not show child objects

    - by gangt
    I have an object with child object(s) and I load it using linq. And I assign it to a treeView's itemssource. treeView.DisplayMemberPath = "Name"; treeView.ItemsSource = tasks; It shows only the parent nodes (task.name), I couldn't figure out how to add children (TaskItems.name). All the examples show HierarchicalData in xaml. I need to do it in code-behind, just like the above code. Is it possible? public class Task { public int Id; public string Name; public bool IsActive; public List<TaskItem> TaskItems = new List<TaskItem>(); } public class TaskItem { public int TaskId; public string Name; public string Value; } -------------- var tasks1 = from t in xd.Descendants("taskheader") select new Task { Id = (int)t.Element("id"), Name = t.Element("name").Value, IsActive = t.Element("isactive").Value == "1", TaskItems = t.Elements("taskdetail").Select(e => new TaskItem { TaskId = (int)e.Element("taskid"), Name = (string)e.Element("name"), Value = (string)e.Element("value"), }).ToList() }; -------------- List<Task> tasks = new List<Task>(); tasks = tasks1;

    Read the article

  • Conditional row count in linq to nhibernate doesn't work

    - by Lucasus
    I want to translate following simple sql query into Linq to NHibernate: SELECT NewsId ,sum(n.UserHits) as 'HitsNumber' ,sum(CASE WHEN n.UserHits > 0 THEN 1 ELSE 0 END) as 'VisitorsNumber' FROM UserNews n GROUP BY n.NewsId My simplified UserNews class: public class AktualnosciUzytkownik { public virtual int UserNewsId { get; set; } public virtual int UserHits { get; set; } public virtual User User { get; set; } // UserId key in db table public virtual News News { get; set; } // NewsId key in db table } I've written following linq query: var hitsPerNews = (from n in Session.Query<UserNews>() group n by n.News.NewsId into g select new { NewsId = g.Key, HitsNumber = g.Sum(x => x.UserHits), VisitorsNumber = g.Count(x => x.UserHits > 0) }).ToList(); But generated sql just ignores my x => x.UserHits > 0 statement and makes unnecessary 'left outer join': SELECT news1_.NewsId AS col_0_0_, CAST(SUM(news0_.UserHits) AS INT) AS col_1_0_, CAST(COUNT(*) AS INT) AS col_2_0_ FROM UserNews news0_ LEFT OUTER JOIN News news1_ ON news0_.NewsId=news1_.NewsId GROUP BY news1_.NewsId How Can I fix or workaround this issue? Maybe this can be done better with QueryOver syntax?

    Read the article

  • LINQ query to find if items in a list are contained in another list

    - by cjohns
    I have the following code: List<string> test1 = new List<string> { "@bob.com", "@tom.com" }; List<string> test2 = new List<string> { "[email protected]", "[email protected]" }; I need to remove anyone in test2 that has @bob.com or @tom.com. What I have tried is this: bool bContained1 = test1.Contains(test2); bool bContained2 = test2.Contains(test1); bContained1 = false but bContained2 = true. I would prefer not to loop through each list but instead use a Linq query to retrieve the data. bContained1 is the same condition for the Linq query that I have created below: List<string> test3 = test1.Where(w => !test2.Contains(w)).ToList(); The query above works on an exact match but not partial matches. I have looked at other queries but I can find a close comparison to this with Linq. Any ideas or anywhere you can point me to would be a great help.

    Read the article

  • How can I find all items beginning with a or â?

    - by Malcolm Frexner
    I have a list of items that are grouped by their first letter. By clicking a letter the user gets alle entries that begin with that letter. This does not work for french. If I choose the letter a, items with â are not returned. What is a good way to return items no matter if they have an accent or not? <% char alphaStart = Char.Parse("A"); char alphaEnd = Char.Parse("Z"); %> <% for (char i = alphaStart; i <= alphaEnd; i++) { %> <% char c = i; %> <% var abcList = Model.FaqList.Where(x => x.CmsHeader.StartsWith(c.ToString())).ToList(); %> <% if (abcList.Count > 0 ) { %> <div class="naviPkt"> <a id="<%= i.ToString().ToUpper() %>" class="naviPktLetter" href="#<%= i.ToString().ToLower() %>"><%= i.ToString().ToUpper() %></a> </div> <ul id="menuGroup<%= i.ToString().ToUpper() %>" class="contextMenu" style="display:none;"> <% foreach (var info in abcList) { %> <li class="<%= info.CmsHeader%>"> <a id="infoId<%= info.CmsInfoId%>" href="#<%= info.CmsInfoId%>" class="abcEntry"><%= info.CmsHeader%></a> </li> <% } %> </ul> <% } %> <% } %>

    Read the article

  • Rss: Bookmark is not working correctly.

    - by shruti
    I'm working on project RSS generation in MVC.Net. in taht i want to make bookmark. for that i have write the code on controller. first there is one aspx page from which subscription page gets open. public ActionResult ViewBlog() { if (Session[SessionVariables.username] == null) { return RedirectToAction("Login", "Home"); } else { return View(classObj.fetchAllBlogs()); } } and coding for subscription is: public ActionResult Rss() { string bcontent = classObj.showBlog(); DateTime postdate = classObj.showPostDate(); List<SyndicationItem> items = new SyndicationItem[] { new SyndicationItem("RSS Blog",bcontent+postdate,null), }.ToList(); RssResult r = new RssResult(); SyndicationFeed feed = new SyndicationFeed("Admin: Blog Posts", "RSS Feed",Request.Url , items); return new RssResult(feed); Developer", "The latest news on ASP.NET, C# and ASP.NET MVC "); } but problem is that when usr clicks on bookmark then intested of opening ViewBlog.aspx it opens the same page. i want to open ViewBlog.aspx. I think the problem is in: SyndicationFeed feed = new SyndicationFeed("Admin: Blog Posts", "RSS Feed",Request.Url , items); Plz help ...!

    Read the article

  • WPF & Linq To SQL binding ComboBox to foreign key

    - by ZeroDelta
    I'm having trouble binding a ComboBox to a foreign key in WPF using Linq To SQL. It works fine when displaying records, but if I change the selection on the ComboBox, that change does not seem to affect the property to which it is bound. My SQL Server Compact file has three tables: Players (PK is PlayerID), Events (PK is EventID), and Matches (PK is MatchID). Matches has FKs for the the other two, so that a match is associated with a player and an event. My window for editing a match uses a ComboBox to select the Event, and the ItemsSource is set to the result of a LINQ query to pull all of the Events. And of course the user should be able to select the Event based on EventName, not EventID. Here's the XAML: <ComboBox x:Name="cboEvent" DisplayMemberPath="EventName" SelectedValuePath="EventID" SelectedValue="{Binding Path=EventID, UpdateSourceTrigger=PropertyChanged}" /> And some code-behind from the Loaded event handler: var evt = from ev in db.Events orderby ev.EventName select ev; cboEvent.ItemsSource = evt.ToList(); var mtch = from m in db.Matches where m.PlayerID == ((Player)playerView.CurrentItem).PlayerID select m; matchView = (CollectionView)CollectionViewSource.GetDefaultView(mtch); this.DataContext = matchView; When displaying matches, this works fine--I can navigate from one match to the next and the EventName is shown correctly. However, if I select a new Event via this ComboBox, the CurrentItem of the CollectionView doesn't seem to change. I feel like I'm missing something stupid! Note: the Player is selected via a ListBox, and that selection filters the matches displayed--this seems to be working fine, so I didn't include that code. That is the reason for the "PlayerID" reference in the LINQ query

    Read the article

  • ASP.Net MVC TDD using Moq

    - by Nicholas Murray
    I am trying to learn TDD/BDD using NUnit and Moq. The design that I have been following passes a DataService class to my controller to provide access to repositories. I would like to Mock the DataService class to allow testing of the controllers. There are lots of examples of mocking a repository passed to the controller but I can't work out how to mock a DataService class in this scenerio. Could someone please explain how to implement this? Here's a sample of the relevant code: [Test] public void Can_View_A_Single_Page_Of_Lists() { var dataService = new Mock<DataService>(); var controller = new ListsController(dataService); ... } namespace Services { public class DataService { private readonly IKeyedRepository<int, FavList> FavListRepository; private readonly IUnitOfWork unitOfWork; public FavListService FavLists { get; private set; } public DataService(IKeyedRepository<int, FavList> FavListRepository, IUnitOfWork unitOfWork) { this.FavListRepository = FavListRepository; this.unitOfWork = unitOfWork; FavLists = new FavListService(FavListRepository); } public void Commit() { unitOfWork.Commit(); } } } namespace MyListsWebsite.Controllers { public class ListsController : Controller { private readonly DataService dataService; public ListsController(DataService dataService) { this.dataService = dataService; } public ActionResult Index() { var myLists = dataService.FavLists.All().ToList(); return View(myLists); } } }

    Read the article

  • linq to xml enumerating over descendants

    - by gh9
    Hi trying to write a simple linq query from a tutorial I read. But i cannot seem to get it to work. I am trying to display both the address in the attached xml document, but can only display the first one. Can someone help me figure out why both aren't being printed. Thank you very much <?xml version="1.0" encoding="utf-8" ?> <Emails> <Email group="FooBar"> <Subject>Test subject</Subject> <Content>Test Content</Content> <EmailTo> <Address>[email protected]</Address> <Address>[email protected]</Address> </EmailTo> </Email> </Emails> Dim steve = (From email In emailList.Descendants("Email") _ Where (email.Attribute("group").Value.Equals("FooBar")) _ Select content = email.Element("EmailTo").Descendants("Address")).ToList() If Not steve Is Nothing Then For Each addr In steve Console.WriteLine(addr.Value) Next Console.ReadLine() End If

    Read the article

  • NHibernate : Root collection with an root object

    - by Daniel
    Hi, I want to track a list of root objects which are not contained by any element. I want the following pseudo code to work: IList<FavoriteItem> list = session.Linq<FavoriteItem>().ToList(); list.Add(item1); list.Add(item2); list.Remove(item3); list.Remove(item4); var item5 = list.First(i => i.Name = "Foo"); item5.Name = "Bar"; session.Save(list); This should automatically insert item1 and item2, delete item3 and item3 and update item5 (i.e. I don't want to call sesssion.SaveOrUpdate() for all items separately. Is it possible to define a pseudo entity that is not associated with a table? For example I want to define the class Favorites and map 2 collection properties of it and than I want to write code like this: var favs = session.Linq<Favorites>(); favs.FavoriteColors.Add(new FavoriteColor(...)); favs.FavoriteMovies.Add(new FavoriteMovie(...)); session.SaveOrUpdate(favs); FavoriteColors and FavoriteMovies are the only properties of the Favorites class and are of type IList and IList. I do only want to persist the these two collection properties but not the Favorites class. Any help is much appreciated.

    Read the article

  • EF in a UserControl can't see the app.config?

    - by Sven
    I just created a user control. This control also makes use of my static Entity Framework class to load two comboboxes. All is well and runs without a problem. Design and runtime are working. Then when I stop the application all the forms that contain my UserControl don't work any more in design time. I just see two errors: Error1: The specified named connection is either not found in the configuration, not intended to be used with the EntityClient provider, or not valid. Error 2: The variable ccArtikelVelden is either undeclared or was never assigned. (ccArtikelVelde is my UserControl) Runtime everything is still working My static EF Repositoy class: public class BSManagerData { private static BSManagerEntities _entities; public static BSManagerEntities Entities { get { if (_entities == null) _entities = new BSManagerEntities(); return _entities; } set { _entities = value; } } } Some logic happening in my UserControl to load the data in the comboboxes: private void LaadCbx() { cbxCategorie.DataSource = (from c in BSManagerData.Entities.Categories select c).ToList(); cbxCategorie.DisplayMember = "Naam"; cbxCategorie.ValueMember = "Id"; } private void cbxCategorie_SelectedIndexChanged(object sender, EventArgs e) { cbxFabrikant.DataSource = from f in BSManagerData.Entities.Fabrikants where f.Categorie.Id == ((Categorie)cbxCategorie.SelectedItem).Id select f; cbxFabrikant.DisplayMember = "Naam"; cbxFabrikant.ValueMember = "Id"; } The only way to make my forms work again, design time, is to comment out the EF part in the UserControl (see above) and rebuild. It's very strange, everything is in the same assembly, same namespace (for the sake of simplicity). Anyone an idea?

    Read the article

  • Problem with inheritance and List<>

    - by Jagd
    I have an abstract class called Grouping. I have a subclass called GroupingNNA. public class GroupingNNA : Grouping { // blah blah blah } I have a List that contains items of type GroupingNNA, but is actually declared to contain items of type Grouping. List<Grouping> lstGroupings = new List<Grouping>(); lstGroupings.Add( new GroupingNNA { fName = "Joe" }); lstGroupings.Add( new GroupingNNA { fName = "Jane" }); The Problem: The following LINQ query blows up on me because of the fact that lstGroupings is declared as List< Grouping and fName is a property of GroupingNNA, not Grouping. var results = from g in lstGroupings where r.fName == "Jane" select r; Oh, and this is a compiler error, not a runtime error. Thanks in advance for any help on this one! More Info: Here is the actual method that won't compile. The OfType() fixed the LINQ query, but the compiler doesn't like the fact that I'm trying to return the anonymous type as a List< Grouping. private List<Grouping> ApplyFilterSens(List<Grouping> lstGroupings, string fSens) { // This works now! Thanks @Lasse var filtered = from r in lstGroupings.OfType<GroupingNNA>() where r.QASensitivity == fSens select r; if (filtered != null) { **// Compiler doesn't like this now** return filtered.ToList<Grouping>(); } else return new List<Grouping>(); }

    Read the article

  • Why is my element variable always null in this foreach loop?

    - by ZeroDivide
    Here is the code: public IEnumerable<UserSummary> getUserSummaryList() { var db = new entityContext(); List<UserSummary> model = new List<UserSummary>(); List<aspnet_Users> users = (from user in db.aspnet_Users select user).ToList<aspnet_Users>(); foreach (aspnet_Users u in users) //u is always null while users is a list that contains 4 objects { model.Add(new UserSummary() { UserName = u.UserName, Email = u.aspnet_Membership.Email, Role = Roles.GetRolesForUser(u.UserName).First(), AdCompany = u.AD_COMPANIES.ad_company_name != null ? u.AD_COMPANIES.ad_company_name : "Not an Advertiser", EmployeeName = u.EMPLOYEE.emp_name != null ? u.EMPLOYEE.emp_name : "Not an Employee" }); } return model; } For some reason the u variable in the foreach loop is always null. I've stepped through the code and the users collection is always populated. The table entity for db.aspnet_Users is the users table that comes with asp.net membership services. I've only added a couple associations to it. edit : image of debugger

    Read the article

  • Storing values in the DataValueField and DataTextField of a dropdownlist using a linq query

    - by user1318369
    I have a website for dance academy where Users can register and add/drop dance classes. In the web page to drop a particular dance, for a particular user, the dropdown displays her registered dances. Now I want to delete one of the dances from the list. So I'll remove the row from the table and also from the dropdownlist. The problem is that everytime the item with the lowest ID (index) is getting deleted, no matter which one the user selects. I think I am storing the DataTextField and DataValueField for the dropdown incorrectly. The code is: private void PopulateDanceDropDown() { // Retrieve the username MembershipUser currentUser = Membership.GetUser(); var username = currentUser.UserName; // Retrive the userid of the curren user var dancerIdFromDB = from d in context.DANCER where d.UserName == username select d.UserId; Guid dancerId = new Guid(); var first = dancerIdFromDB.FirstOrDefault(); if (first != null) { dancerId = first; } dances.DataSource = (from dd in context.DANCER_AND_DANCE where dd.UserId == dancerId select new { Text = dd.DanceName, Value = dd.DanceId }).ToList(); dances.DataTextField = "Text"; dances.DataValueField = "Value"; dances.DataBind(); } protected void dropthedance(object o, EventArgs e) { String strDataValueField = dances.SelectedItem.Value; int danceIDFromDropDown = Convert.ToInt32(strDataValueField); var dancer_dance = from dd in context.DANCER_AND_DANCE where dd.DanceId == danceIDFromDropDown select dd; foreach (var dndd in dancer_dance) { context.DANCER_AND_DANCE.DeleteOnSubmit(dndd); } try { context.SubmitChanges(); } catch (Exception ex) { Console.WriteLine(ex); } } The problem is in the line: String strDataValueField = dances.SelectedItem.Value; The strDataValueField is always getting the minimum id from the list of dance item ids in the dropdown (which happens by default). I want this to hold the id of the dance selected by the user.

    Read the article

  • Filtering two arrays to avoid Inf/NaN values

    - by Gacek
    I have two arrays of doubles of the same size, containg X and Y values for some plots. I need to create some kind of protection against Inf/NaN values. I need to find all that pairs of values (X, Y) for which both, X and Y are not Inf nor NaN If I have one array, I can do it using lambdas: var filteredValues = someValues.Where(d=> !(double.IsNaN(d) || double.IsInfinity(d))).ToList(); Now, for two arrays I use following loop: List<double> filteredX=new List<double>(); List<double> filteredX=new List<double>(); for(int i=0;i<XValues.Count;i++) { if(!double.IsNan(XValues[i]) && !double.IsInfinity(XValues[i]) && !double.IsNan(YValues[i]) && !double.IsInfinity(YValues[i]) ) { filteredX.Add(XValues[i]); filteredY.Add(YValues[i]); } } Is there any way of filtering two arrays at the same time using LINQ/Lambdas, as it was done for single array?

    Read the article

  • Shaping EF LINQ Query Results Using Multi-Table Includes

    - by sisdog
    I have a simple LINQ EF query below using the method syntax. I'm using my Include statement to join four tables: Event and Doc are the two main tables, EventDoc is a many-to-many link table, and DocUsage is a lookup table. My challenge is that I'd like to shape my results by only selecting specific columns from each of the four tables. But, the compiler is giving a compiler is giving me the following error: 'System.Data.Objects.DataClasses.EntityCollection does not contain a definition for "Doc' and no extension method 'Doc' accepting a first argument of type 'System.Data.Objects.DataClasses.EntityCollection' could be found. I'm sure this is something easy but I'm not figuring it out. I haven't been able to find an example of someone using the multi-table include but also shaping the projection. Thx,Mark var qry= context.Event .Include("EventDoc.Doc.DocUsage") .Select(n => new { n.EventDate, n.EventDoc.Doc.Filename, //<=COMPILER ERROR HERE n.EventDoc.Doc.DocUsage.Usage }) .ToList(); EventDoc ed; Doc d = ed.Doc; //<=NO COMPILER ERROR SO I KNOW MY MODEL'S CORRECT DocUsage du = d.DocUsage;

    Read the article

  • Scala always returning true....WHY?

    - by jhamm
    I am trying to learn Scala and am a newbie. I know that this is not optimal functional code and welcome any advice that anyone can give me, but I want to understand why I keep getting true for this function. def balance(chars: List[Char]): Boolean = { val newList = chars.filter(x => x.equals('(') || x.equals(')')); return countParams(newList, 0) } def countParams(xs: List[Char], y: Int): Boolean = { println(y + " right Here") if (y < 0) { println(y + " Here") return false } else { println(y + " Greater than 0") if (xs.size > 0) { println(xs.size + " this is the size") xs match { case xs if (xs.head.equals('(')) => countParams(xs.tail, y + 1) case xs if (xs.head.equals(')')) => countParams(xs.tail, y - 1) case xs => 0 } } } return true; } balance("()())))".toList) I know that I am hitting the false branch of my if statement, but it still returns true at the end of my function. Please help me understand. Thanks.

    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

  • Merging ILists to bind on datagridview to avoid using a database view

    - by P.Bjorklund
    In the form we have this where IntaktsBudgetsType is a poorly named enum that only specifies wether to populate the datagridview after customer or product (You do the budgeting either after product or customer) private void UpdateGridView() { bs = new BindingSource(); bs.DataSource = intaktsbudget.GetDataSource(this.comboBoxKundID.Text, IntaktsBudgetsType.PerKund); dataGridViewIntaktPerKund.DataSource = bs; } This populates the datagridview with a database view that merge the product, budget and customer tables. The logic has the following method to get the correct set of IList from the repository which only does GetTable<T>.ToList<T> public IEnumerable<IntaktsBudgetView> GetDataSource(string id, IntaktsBudgetsType type) { IList<IntaktsBudgetView> list = repository.SelectTable<IntaktsBudgetView>(); switch (type) { case IntaktsBudgetsType.PerKund: return from i in list where i.kundId == id select i; case IntaktsBudgetsType.PerProdukt: return from i in list where i.produktId == id select i; } return null; } Now I don't want to use a database view since that is read-only and I want to be able to perform CRUD actions on the datagridview. I could build a class that acts as a wrapper for the whole thing and bind the different table values to class properties but that doesn't seem quite right since I would have to do this for every single thing that requires "the merge". Something pretty important (and probably basic) is missing the the thought process but after spending a weekend on google and in books I give up and turn to the SO community.

    Read the article

< Previous Page | 18 19 20 21 22 23 24 25 26 27 28 29  | Next Page >