Menu
  • HOME
  • TAGS

Only parameterless constructors and initializers are supported in LINQ to Entitier in dropdown

Tag: .net,asp.net-mvc-5

I have this controller

public ActionResult Create()
{
    var db = new MyDbContext();
    IEnumerable<SelectListItem> items = db.FileUploadCategories

        .Select(c => new SelectListItem {
            Value = c.ParentCategoryID.ToString(),
            Text = "--" + c.CategoryName
        });

    ViewBag.Categories = items;
    return View();
}

And a view like this

 @Html.DropDownList("ParentCategoryID", (IEnumerable<SelectListItem>)ViewBag.Categories, "-- Select --", new { @class = "form-control" })

This gives me the this result on the website

<select>
<option value="0">Test</option>
<option value="1">Test</option>
<option value="1">Test</option>
<option value="2">Test</option>
<option value="2">Test</option>
</select>

As you can see, some value are the same, which is because some ParentCategoryID from the controller is the same which is correct. What I would like to do is add a "-" in the text for each text in the options which will be determined by how large the value is. I want to add 3 ' - ' in text if the value is 3 and if the value is five, I want add five '-----' before the test in text. I want a result similar to this.

<select>
<option value="0">Test</option>
<option value="1">-Test</option>
<option value="1">-Test</option>
<option value="2">--Test</option>
<option value="2">--Test</option>
</select>

Notice the lines before the test.

I have tried to update my controller to

Text = new String('-',c.ParentCategoryID) + c.CategoryName

Which gives me the error message

An exception of type 'System.NotSupportedException' occurred in EntityFramework.SqlServer.dll but was not handled in user code

Additional information: Only parameterless constructors and initializers are supported in LINQ to Entities.

Best How To :

You query needs to be able to be represented as a SQL statement, but new String('-',c.ParentCategoryID) can't be. Materialize your query as a List<T> first

var items = db.FileUploadCategories.ToList().Select(c => new SelectListItem()
{
    Value = c.ParentCategoryID.ToString(),
    Text= string.Format("{0}{1}", new String('-',c.ParentCategoryID), c.CategoryName)
}).ToList();

How does convert.ToString(C0) behave?

c#,.net

You can brute force search the string for any currency symbols and change them to whatever character you want eg: string s = "$"; foreach (var c in s) { var category = CharUnicodeInfo.GetUnicodeCategory(c); if (category == UnicodeCategory.CurrencySymbol) { //Force convert the char to what every character you want }...

Unconstrained type parameters casting

c#,.net,types,casting

The compiler sees the T2 and T identifiers and helpfully informs you that those types seem unrelated. That's absolutely correct, as they have no relation: there are no generic constraints that would assert any relations between them (I'm not saying that would be useful here though :) ). Whether this...

Feature-specific compatibility of a .NET 4.5 application on a system with .NET 4.0

c#,.net,zipfile

The easiest way to do this is probably to load the required code dynamically. You could use reflection to look for the required assembly, class and members if .NET 4.5 is detected. You could cache the results in delegates, to avoid reflecting every time. You could also use a plug-in...

Visual Studio Assembly force-installs Target Framework

c#,.net,visual-studio-2013,.net-framework-version

The targeted .NET version is the only version that the app will depend upon by default. Visual Studio will not automatically add higher and backwards compatible releases. Do this manually by adding other .NET versions to a configuration file: On the Visual Studio menu bar: Choose Project; Add New Item;...

Best approach to upgrade MVC3 web app to MVC5?

c#,.net,asp.net-mvc,asp.net-mvc-5

There's a handy documented guide by Rick Anderson which he wrote to upgrade from MVC4, the same applies to you with the exception of the fact that the "Old version" of DLLs he mentions will be different to the ones that you will have, but the outcome will still be...

MVC 5 OWIN login with claims and AntiforgeryToken. Do I miss a ClaimsIdentity provider?

asp.net-mvc,asp.net-mvc-4,razor,asp.net-mvc-5,claims-based-identity

Your claim identity does not have ClaimTypes.NameIdentifier, you should add more into claim array: var claims = new List<Claim> { new Claim(ClaimTypes.Name, "Brock"), new Claim(ClaimTypes.Email, "[email protected]"), new Claim(ClaimTypes.NameIdentifier, "userId"), //should be userid }; To map the information to Claim for more corrective: ClaimTypes.Name => map to username ClaimTypes.NameIdentifier => map...

Programmatically accessing TFS history [closed]

c#,.net,powershell,tfs

Shai Raiten's Blog is great for learning the TFS API. For getting file history - read this post: http://blogs.microsoft.co.il/shair/2014/09/10/tfs-api-part-55-source-control-get-history/...

Microsoft Band and WPF

.net,wpf,dll,microsoft-band,.net-core

The current Band SDK does not support Windows desktop (i.e. Win32) applications. It supports only Windows Store and Windows Phone (i.e. WinRT) applications. Portable libraries can be confusing as the terms '.NETCore' and 'netcore451' refer to the Windows Store version of the .NET framework....

How can I determine if an object of anonymous type is empty?

c#,.net

Anonymous types do not provide operator overloads for ==, although it wouldn't matter in this case since one of the arguments is typed object. However the C# compiler does provide Equals, GetHashCode, and ToString implementations. Use the static object.Equals, method which will do the appropriate null checks and then call...

Catch concurrency exception in EF6 to change message to be more user friendly

c#,asp.net,.net,entity-framework,entity-framework-6

You are executing an asynchronous method. This means that any exceptions will be thrown when you call await on the returned task or when you try to retrieve the results using await myTask; You never do so, which means that the exception is thrown and caught higher up your call...

External Datepicker not working

javascript,jquery,.net

Apparently your Array has no map method, which is part of ECMA-262 edition 5 and which your JS engine seems not to support? You can implement Array.prototype.map manually by taking it from somewhere like https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Global_Objects/Array/map.

string.Format is not giving correct output when INR currency symbol (Rs.) come to display

c#,asp.net-mvc-5,devexpress

Your Model.CurrencySymbol string can have some symbols that can be interpreted as format specifier symbols. You can use literal string delimiter ('string', "string") so your currency symbol string will be copied to the result. For example: column.PropertiesEdit.DisplayFormatString = string.Format("'{0}' #,0.00", Model.CurrencySymbol); //Here comes string delimiters: ↑ ↑ Also you can...

Automapper AfterMap function initialising classes

.net,vb.net,automapper

The objects have values in them because they are called after Mapping.Map function is called and that's where actual object with values is passed and then AfterMap function is called and that's how it has the values in it.

Set default value for string prompt

c#,.net,autocad,autocad-plugin

I paste you some code as example for the different prompts : using System; using System.Collections.Generic; using Autodesk.AutoCAD.EditorInput; using Autodesk.AutoCAD.Geometry; using Autodesk.AutoCAD.ApplicationServices; namespace EditorUtilities { /// <summary> /// Prompts with the active document ( MdiActiveDocument ) /// </summary> public class EditorHelper : IEditorHelper { private readonly Editor _editor; public EditorHelper(Document...

I want to upload video on youtube using client side login. without open web page permission

c#,.net,google-api,youtube-api,google-api-dotnet-client

Your code is doing is doing everything correctly. The YouTube API doesn't allow for pure server authentication (Service Account). The only option available to you to upload files will be to use Oauth2 and authenticate your code the first time. I just sugest you make one small change add filedatastore....

MVC route attribute no controller

asp.net-mvc,asp.net-mvc-5,asp.net-mvc-routing

Ok so ranquild's comment pushed me in the right direction. In my route config, I had the default route of routes.MapRoute( name: "Default", url: "{controller}/{action}/{id}", defaults: new { controller = "Home", action = "Index", id = UrlParameter.Optional } ); So that my homepage would still work on the url with...

String Format: How to add any number of zeros before string

c#,.net

int num = 4; string a = num.ToString("D4"); Documentation...

Dependency Injection for concrete .Net classes

c#,.net,dependency-injection,ninject

If TcpServer is sealed and implements no interfaces, but you still want to decouple a client from its particular implementation, you'll have to define an interface that the client can talk to, as well as an Adapter from TcpServer to the new interface. It can be tempting to extract an...

Move windows form from a picturebox in C#

c#,.net,winforms,picturebox

Refer this code: private bool draging = false; private Point pointClicked; private void pictureBox1_MouseMove(object sender, MouseEventArgs e) { if (draging) { Point pointMoveTo; pointMoveTo = this.PointToScreen(new Point(e.X, e.Y)); pointMoveTo.Offset(-pointClicked.X, -pointClicked.Y); this.Location = pointMoveTo; } } private void pictureBox1_MouseDown(object sender, MouseEventArgs e) { if (e.Button == MouseButtons.Left) { draging = true;...

Consuming and exposing webservices in one project (.NET)

.net,web-services,rest,soap

If you are trying to enrich the data from one source and combine that with information from another source, I think this is a decent solution. I think it is better to have one single point to talk to (your REST service), than to have two in your application and...

Custom drawing using System.Windows.Forms.BorderStyle?

c#,.net,vb.net,winforms,custom-controls

If you want to get results that reliably look like the BorderStyles on the machine you should make use of the methods of the ControlPaint object. For testing let's do it ouside of a Paint event: Panel somePanel = panel1; using (Graphics G = somePanel.CreateGraphics()) { G.FillRectangle(SystemBrushes.Window, new Rectangle(11, 11,...

How to use ajax to post json string to controller method?

jquery,asp.net-mvc,visual-studio-2013,asp.net-mvc-5

Your action method is expecting a string. Create a javascript object, give it the property "data" and stringify your data object to send along. Updated code: $.ajax({ type: 'post', dataType: 'json', url: 'approot\Test', data: { "json": JSON.stringify(data) }, success: function (json) { if (json) { alert('ok'); } else { alert('failed');...

MySQL database to combo box using mysqldatareader in c#.net [closed]

c#,mysql,sql,.net

Wow... Suppost your combox name is cbProducts, and you want fill it with the colum "description" of the query MySQL database to combo box using mysqldatareader in c#.net MySqlCommand cmd = new MySqlCommand("select * from product", connection); MySqlDataReader dread = cmd.ExecuteReader(); while (dread.Read()) { cbProducts.Items.Add(dread("description"); } ...

OpenXml.WordProcessing.Justification always comes as OpenXmlUnknownElement

.net,ms-office,openxml,openxml-sdk

You need to read the documentation. TableCellProperties doesn't take the a Justification element. Link If you are trying to align elements within a cell, you need to put it into ParagraphProperties....

ASP.NET MVC posting list from view to controller

c#,.net,asp.net-mvc,razor

That's probably a good candidate for an EditorTemplate to be honest, that way you don't have any issues with prefixing: @Html.EditorFor(m => m.TechnologyFilters) Without using an editor template though, a technique you can use is to specify the prefix in your partial declaration within the ViewDataDictionary, by doing: Html.RenderPartial("_TechnologyFilters", Model.TechnologyFilters,...

Listing directories by content size using C# [closed]

c#,.net,windows,linq

A small example here: class DirectorySize { public string DirectoryName; public long DirectorySizes; } public class Program { static void Main(string[] args) { string[] cDirectories = Directory.GetDirectories("C:\\"); List<DirectorySize> listSizes = new List<DirectorySize>(); for (int i = 0; i < cDirectories.Length; i++) { long size = GetDirectorySize(cDirectories[i]); if(size != -1) {...

inconsistent timing from .net StopWatch

c#,.net,timing,stopwatch,cudafy.net

As the TotalMilliseconds is constantly incrementing & you are trying to find differences between points in time, you need to subtract the sum of the preceding differences after the second one, hence : tIQR = watch.Elapsed.TotalMillisconds - (tHistogram + tHistogramSum); & tThresholdOnly= watch.Elapsed.TotalMillisconds - (tHistogram + tHistogramSum + tIQR); ...

Web API - Set each thread with the HttpRequestMessage id?

c#,.net,multithreading,task-parallel-library,web-api

For context related problems, you can use CallContext.LogicalSetData and CallContext.LogicalGetData, which is merely an IDictionary<string, object> which flows between contexts, and has a copy-on-write (shallow copy) semantics. Since your data is immutable (according to the docs), you can map your correlation id to your threads managed thread id: protected async...

Where to store an mp4 file in my project?

.net,vb.net,visual-studio,mp4

Try going Project>"Project Name" Properties>Resources>Add Resource>Add Existing File This should add the file into your resources folder. You can then access any file by going My.Resources.Name_Of_Resource...

MvcSiteMapProvider - Enhanced bootstrap dropdown menu

c#,twitter-bootstrap,asp.net-mvc-5,mvcsitemapprovider,mvcsitemap

node.Descendants should be node.Children Learn the difference on Descendants and Children here, CSS Child vs Descendant selectors (Never mind the post beeing about CSS, this is a generic pattern)...

Is Serialization the same as GetBytes?

.net

No, GetBytes() just converts a string to its binary represenation using the asked encoding. So it does serialize, but it is very specific to strings. When you want to serialize any object to bytes, you could use the BinaryFormatter. More about how to serialize an object using the BinaryFormatter can...

Foreign key not updating in entity frame work

c#,.net,entity-framework,foreign-keys

Base on Entity Framework does not update Foreign Key object I created public string ModifiedBy { get; set; } [DataMember] [ForeignKey("ModifiedBy")] public User ModifiedUser { get; set; } That means I additionally introduced a primitive type(string ModifiedBy ) for Modified User and specified ForeignKey. That resolved my issue...

Unhandled exceptions and background workers

.net,exception-handling,backgroundworker

The other threads will carry on. Only the thread used by the BackgroundWorker will crash. An unhandled exception will be thrown. Since there is no exception handling in the event handler, it will get caught by the CLR as a last resort. This will not influence other threads....

SpecFlow Ambiguity in bindings

c#,.net,bdd,specflow

As @perfectionist has pointed out your problem is with your regexes. One is consuming all of the chars for both. Try this instead: Feature: ConversionUnencrypted Pdf-Pdf @mytag Scenario Outline: ConversionUnencrypted Pdf-Pdf Given I get Inputs Folder and list of Files '<inputFolder>' then '<getInputTokens>' Given I get '<outputDirectory>' ... and the...

XElement.Value is stripping XML tags from content

c#,.net,xml,xml-parsing,xelement

As others have said, this format is truly horrible, and will break as soon as the XML embedded in the JSON will contain double quotes (because in the JSON they will be encoded as \", which will make the XML invalid). The JSON should really be embedded as CDATA. Now,...

Related entity not loaded

c#,.net,entity-framework

Mark your relation property with virtual keyword for EF's proxy to be able to overload it: [ForeignKey("SchoolClassId")] public virtual SchoolClass SchoolClass { get; set; } Also, be sure that context's DbContext.Configuration.ProxyCreationEnabled property value is set to true (by default it is). These two conditions enabling lazy loading of your relations....

how can I add a column to IQueryable object and modify its values

c#,.net,linq,grid,devexpress

Simple example for using a non-anonymous class. public class MyLovelyClass { public Int32 Number { get; set; } public bool Selection { get; set; } } var packs = from r in new XPQuery<Roll>(session) select new MyLovelyClass() { Number = r.number }; gcPack.DataSource = packs; ...

Does MongoDB successful insert guarantee populated ID's?

c#,.net,mongodb-csharp,mongodb-csharp-2.0

Yes. If the operation completed without errors you are guaranteed that the documents have an ID (either created by you before the operation or by the driver in the operation itself). Moreover, since the IDs are generated by the driver itself (client-side) before calling the MongoDB server there's a good...

Why when trying to upload a video file to youtube i'm getting InvalidCredentialsException?

c#,.net,youtube,youtube-api,google-client-login

ClientLogin (login and password) was deprecated as of April 20, 2012 and turned off on May 26 2015. This code will not longer work you need to switch to using Oauth2. I would like to also recomed you use the new Google client library Install-Package Google.Apis.YouTube.v3 ...

Application is missing required files

c#,.net,windows,winforms,sharpdevelop

Your program is looking for compas.ico inside the build directory, while it probably resides in some other directory in your project.

QUERY IN C# ,where statement

c#,.net,select

I Assumed that you are using SQL this a generic query for your question: SQLCommand cmd = new SQLCommand(); cmd = "SELECT DEPT_ID FROM PERSONNEL_TEMP.DEPARTMENT WHERE DEPARTMENT_NAME= '" + combobox1.Text + "'"; here is what I recommend SQLCommand cmd = new SQLCommand(); cmd = "SELECT DEPT_ID FROM PERSONNEL_TEMP.DEPARTMENT WHERE DEPARTMENT_NAME=...

Capturing group recursively inside non-capturing group?

.net,regex

The .net regex implementation gives the possibility to store the substrings of a repeated capture group. So with this pattern that describes the whole string: \A(?:(\d+(?:-\d+)?)(?:,|\z))+\z (where \A and \z stand for the start and the end of the string) you obtain all the values in capture group 1 with...

How does the Take() method work in LINQ

c#,.net,linq,entity-framework

See Return Or Skip Elements in a Sequence. Take(N) will add TOP N to your SQL and only retrieve N records. For example (using my own SQL Server 2014 with EF 6.1): This LINQ: var query = await dbContext.Lookup .Where(w => w.LookupCd == '1') .Take(10) .ToListAsync(); Generates this SQL: SELECT...

Regex to remove `.` from a sub-string enclosed in square brackets

c#,.net,regex,string,replace

To remove all the dots present inside the square brackets. Regex.Replace(str, @"\.(?=[^\[\]]*\])", ""); DEMO To remove dot or ?. Regex.Replace(str, @"[.?](?=[^\[\]]*\])", ""); ...

DialogBox with value verifications

c#,.net,winforms

The problem is you're trying to enable or disable the button when checking individual textboxes and they're conflicting with each other, instead the logic needs to be at a higher level. Change your textbox validation function to return a bool, and use that in ValidateAll to determine whether or not...

Formatting large numbers in C#

c#,.net,unity3d,formatting

I am using this method in my project, you can use too. Maybe there is better way, I dont know. public void KMBMaker( Text txt, double num ) { if( num < 1000 ) { double numStr = num; txt.text = numStr.ToString() + ""; } else if( num < 1000000...

Knockout js unable to bind data using observableArray

knockout.js,asp.net-mvc-5

self.Employees.push(data); should be self.Employees(data);

How to send Ctrl+S through SendKeys.Send() method to save a file(save as dialog)

c#,.net,windows,sendkeys

I believe you need to use: SendKeys.SendWait("^(s)"); Instead of: SendKeys.SendWait("^%s?"); Have a look at https://msdn.microsoft.com/en-us/library/system.windows.forms.sendkeys.send(v=vs.110).aspx for more information....

Linq Conditional DefaultIfEmpty query filter

c#,linq,asp.net-mvc-5,linq-query-syntax

I solved it by adding the filter after the initial query, checking if the e.PractitionerProfiles were null. var query = from e in _repository.GetAll<Entity>() from u in e.Users where (e.AuditQuestionGroupId != null ? e.AuditQuestionGroupId : 0) == this.LoggedInEntity.AuditQuestionGroupId from p in e.PractitionerProfiles.DefaultIfEmpty() select new { entity = e, user =...