Menu
  • HOME
  • TAGS

Understanding ASp.net Identity key points

Tag: asp.net-mvc-5,entity-framework-6,asp.net-identity-2

I am an Asp.net developer but very much new to the Asp.net Identity framework. I have been studying the sample application and followed some tutorials too on Identity but still I am not able to grasp the concept completely. I have very firm grip over Asp.net membership but Identity seems nothing like membership. I will explain what I have done so far.

I am creating a simple application in which I am following code first approach. I have created entity model for User which inherits from IdentityUser and has some extra fields. Below is entity model for User.

public class User : IdentityUser
{
    public int? CompanyID { get; set; }

    public bool? CanWork { get; set; }

    public bool? CanSearch { get; set; }

    public Company Company { get; set; }
}

Now in the examples people use the name ApplicationUser but for my own purpose I have used name User. Also there is a method in User or ApplicationUser model which is,

public async Task<ClaimsIdentity> GenerateUserIdentityAsync(UserManager<User> manager)
    {
        CookieAuthenticationOptions.AuthenticationType
        var userIdentity = await manager.CreateIdentityAsync(this, DefaultAuthenticationTypes.ApplicationCookie);
        // Add custom user claims here
        return userIdentity;
    }

I am unable to understand the purpose of this method. Also from an example I have used the following model for Role,

public class Role : IdentityRole
{
    public Role()
    {

    }

    public Role(string roleName, string description)
        : base(roleName)
    {
        this.Description = description;
    }

    public string Description { get; set; }
}

I understand that an extra field is added but I am unable to understand the purpose of overloaded constructor.

The above mentioned confusions are secondary. My primary confusion is that I am familiar that when I create entity models I use DbSet and DbContext and when I call any entity framework method to access the database, the database is created/drop created whichever scheme I am following.

In Identity which method is responsible for creating the Identity tables in the database? I have a IdentityConfig file in which I declare ApplicationUserManager and ApplicationSignInManager. I have also a Startup file. Previously I had only one Startup file in the App_Start folder and when I run the application and tried to accessed any Identity methods it gave me error and was not creating database. I then made the class as partial and created another partial class with same name at the root and then the exception was gone and tables were created. So Startup class is responsible for creating Identity tables? There are extra columns created automatically in the AspNetUsers like PhoneNumber, PhoneNumberConfirmed, TwoFactorEnabled. I don't need these extra columns. Can I remove these? Can I change the names of the Identity tables that are created?

I know these are very basic questions and not one question at all but if I was unable to find some basic tutorial or example for beginners then it would be very beneficial. What I have found are describing those things which I don't need or making me confuse. I want to understand and have control how Identity should work in my application but till now it seems to me that neither I am grasping it completely and nor being able to make is adjustable to my needs. Its like tutorials and example are teaching me how to make sentences but I am unable to understand the alphabets. :(

Best How To :

First of all you have to define the model - as you're doing - implementing the right interfaces.
Let's say you want to create a user for your application:

public class MyUser : IdentityUser<string, MyUserLogin, MyUserRole, MyUserClaim>
{
    public string CompanyName { get; set; }
}

As you can see I've implemented the IdentityUser interface (namespace Microsoft.AspNet.Identity.EntityFramework).

I've specified what type of identifier I want to use for my primary key (string) and included my custom objects to manges login, roles and claims.

Now we can defined the role object:

public class MyRole : IdentityRole<string, MyUserRole>
{
}

Again there's a type and the class I've defined for the management of users belonging to to a role.

public class MyUserRole : IdentityUserRole<string>
{
}

MyUserLogin is going to implement IdentityUserLogin<string>.
MyUserClaim is going to implement IdentityUserClaim<string>.

As you can see each interface need a type for the primary key.

The second step is to create the user store:

public class MyUserStore:  UserStore<MyUser, MyRole, string, MyUserLogin, MyUserRole, MyUserClaim>
{
    public MyUserStore(MyContext context)
        : base(context)
    {
    }
}

Again we have defined what user, role, login etc etc we want to use.
We need UserStore cause our UserManager is going to need one.

If you're planning to manage roles and associate roles with each user you have to create your RoleStore definition.

public class MyRoleStore : RoleStore<MyRole, string, MyUserRole>
{
    public DaufRoleStore(ApplicationDatabaseContext context) : base(context)
    {
    }
}

Now you can create your UserManager. The UserManager is the real responsible of saving changes to the UserStore.

public class ApplicationUserManager : UserManager<MyUser, string>
{
    public ApplicationUserManager(IUserStore<MyUser, string> store)
        : base(store)
    {

    }

    public static ApplicationUserManager Create(IdentityFactoryOptions<ApplicationUserManager> options, IOwinContext context)
    {
        var manager = new ApplicationUserManager(new MyUserStore(context.Get<MyContext>()));

        manager.UserValidator = new UserValidator<MyUser, string>(manager)
        {
        AllowOnlyAlphanumericUserNames = false,
        RequireUniqueEmail = true
        };

        manager.PasswordValidator = new PasswordValidator()
        {
        RequiredLength = 5,
        RequireNonLetterOrDigit = false,     // true
        // RequireDigit = true,
        RequireLowercase = false,
        RequireUppercase = false,
        };

        return (manager);
    }
}

This class has a static method which will create a new UserManager for you.
Interesting to note that you can include some validation rules you might need to validate password etc etc.

Last thing is to create or database context.

public class MyContext : IdentityDbContext<MyUser, MyRole, string, MyUserLogin, MyUserRole, MyUserClaim>
{
    public MyContext(): base("<your connection string here>")
    {

    }

    public static MyContext Create()
    {
        return new MyContext();
    }

    protected override void OnModelCreating(DbModelBuilder modelBuilder)
    {
        base.OnModelCreating(modelBuilder);

        modelBuilder.Entity<MyUser>()
            .ToTable("Users");

        modelBuilder.Entity<MyRole>()
            .ToTable("Roles");

        modelBuilder.Entity<MyUserRole>()
            .ToTable("UserRoles");

        modelBuilder.Entity<MyUserClaim>()
            .ToTable("UserClaims");

        modelBuilder.Entity<MyUserLogin>()
            .ToTable("UserLogins");
    }
}

As you can see I've used the model builder to change the names all the tables. You can define keys or fields type or tables relations here.

This is the place where you're going to attach your custom classes you want to manage in your context:

public DbSet<MyCustomer> Customers{ get; set; }

Again MyContext has a Create method which returns a new context:

public static MyContext Create()
{
    return new MyContext();
}

Now you should have a startup class where you're going to bootstrap your stuff:

[assembly: OwinStartup(typeof(ASPNETIdentity2.Startup))]

namespace ASPNETIdentity2
{
    public class Startup
    {
        public void Configuration(IAppBuilder app)
        {
            app.CreatePerOwinContext(MyContext.Create);
            app.CreatePerOwinContext<ApplicationUserManager>(ApplicationUserManager.Create);
        }
    }
}

Here you're going to create your database context and your user manager you can use in your application.

Notice the first line:

[assembly: OwinStartup(typeof(ASPNETIdentity2.Startup))]

This is needed cause you're telling your environment that is the startup class which needs to be called at ... startup.

Now in your controllers you can simply refer to your UserManager doing something like this:

HttpContext.GetOwinContext().GetUserManager<ApplicationUserManager>();

How can you create your tables?

In Visual Studio go to TOOLS -> NuGet Packager Manager -> Package Manager Console.

In the window there's a combobox "Default Project". Choose your ASP.NET MVC project.
Run this command:

Enable-Migrations

It will create a file Configuration.cs in a new folder called Migrations.
If you want to create your database you need to open that file and change the AutomaticMigrationsEnabled to true:

public Configuration()
{
    AutomaticMigrationsEnabled = true;
}

Again, from Package Manager Console, you can run:

Update-Database

and all your tables will appear in your database. Don't forget your connection string.

You can download this github project to see how everything works.
You can check these two answers with some other info.

The first of the two has got some links to a blog where you can learn all these things.

NOTE:

You have to do all this if you want to customized every single bit of your environment.

How to append Urls in angular routing?

asp.net,angularjs,asp.net-mvc-5,angularjs-ng-repeat,angular-ui-router

You need to change your $routeProvider.when url option, that will accept two parameter one would be albumType & other would be alubmName. You that you could get those values in your b1Ctrl using $routeParams service. Markup <li ng-repeat="album in albums"> <a ng-href="/albums/{{alubm.type}}/{{album.name}}">{{album.name}}</a> </li> Code when('/albums/:albumType/:albumName', { templateUrl: 'AlbumsList.html', controller: 'b1Ctrl'...

How do I properly send __RequestVerificationToken with an ajax request in MVC5

ajax,asp.net-mvc,asp.net-mvc-5

x = $.post(window.location, {data: $('#editDrinkForm').serialize()}) is wrong. Do this: x = $.post(window.location, data: $('#editDrinkForm').serialize()) (some credit to stephen's comment)...

How to augment actionlink with route values at runtime with JavaScript in ASP.NET MVC 5?

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

I'm not sure this is the best way of doing this, but I'll provide you with my solution to this problem. The main idea is to generate the link with all required parameters and format the href with javascript, like string.Format in c#. Generate the link: @Html.ActionLink("Link", "action", "controller", new...

LINQ: Searching inside child entities

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

One option would be to use LINQ .Any(): var stringResults = db.Properties.Where(x => x.Address.Contains(id) || /* Other conditions || */ x.BayOptions.Any(g => g.Description.Contains(id))); Here, x.BayOptions.Any(g => g.Description.Contains(id)) will return true if any of the BayOptions values have a description which contains the ID....

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...

Future plans to consider for asp.net mvc 5.2 web application, with releasing asp.net mvc6 (vnext)

asp.net,asp.net-mvc,asp.net-mvc-5,asp.net-mvc-6,asp.net-mvc-5.2

I would simply recommend following the standard best practice of n-tier architecture and keeping logic related to things like querying a database in class libraries. MVC 6 is drastically different from previous versions, so there's no easy migration. You'll basically need to start a brand new project and move...

Error while connecting to database in code-first Entity Framework

c#,ef-code-first,entity-framework-6

There are a couple of problems here. Firstly, DbContext already imlpements IDisposable so you don't need that. It's not a problem having it there, but it is redundant. Secondly your List<> properties should be using DbSet<> instead: public class Context : DbContext { public Context() : base("EcommConnectionString") { } public...

Knockout js unable to bind data using observableArray

knockout.js,asp.net-mvc-5

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

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)...

How detailed should your repository be? Testing issues [closed]

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

Welcome to chasing the windmill of 100% test coverage :) You're right, there isn't a ton of value in unit testing a controller method which doesn't actually contain any logic. (Somewhere in the world, Uncle Bob just spilled his coffee.) There is some, though... By explicitly defining the expectations (in...

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...

Entity Framework connection factory not working

c#,entity-framework,connection,entity-framework-6,sqlanywhere

It is important that the configuration section in the app.config does not exists, because it has a higher priority.

Am I required to put multiple Entity Framework Models in their own projects in the same solution?

c#,entity-framework-6

One way to resolve this is to create each of your models within a separate folder. By default, Visual Studio creates classes in a namespace corresponding to the folder in which they are created. Creating each model in a separate folder should create each model in a separate namespace.

Asp.Net MVC 5 + Bootstrap. How make inputs fit screen width?

css,asp.net,asp.net-mvc,twitter-bootstrap,asp.net-mvc-5

The default MVC5 template has a css rule in Site.css: input, select, textarea { max-width: 280px; } I usually remove this rule. It causes problems with Bootstrap v3 input group where the input box does not extend to its container's width....

Unable to cast code first

c#,entity-framework,entity-framework-6,code-first

Since User.Operations is supposed to be a collection property (and not a reference property), you need to use HasMany: modelBuilder.Entity<User>() .HasMany(a => a.Operations) .WithOptional() .WillCascadeOnDelete(true); Originally, you were telling EF that User.Operations is a reference property, which causes an error when you try to assign a collection to it....

EPPlus: how can I assign border around each cell after I apply LoadFromCollection?

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

If I know the amount of columns the model has, I can count the number of rows with a function and do this: var modelRows = exportQuery.Count()+1; string modelRange = "D1:F" + modelRows.ToString(); var modelTable = worksheet.Cells[modelRange]; Or, with more context. I verified that EPPlus will accept a string variable...

Web API AuthorizeAttribute does not return custom response

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

You should override the OnAuthorization method, that use the IsAuthorized and flushs the response, or force a flush at your method. Makes more sense fill the response where the filter manipulates It.

DbSet.Attach(entity) vs DbContext.Entry(entity).State = EntityState.Modified

c#,entity-framework,entity-framework-6

When you do context.Entry(entity).State = EntityState.Modified;, you are not only attaching the entity to the DbContext, you are also marking the whole entity as dirty. This means that when you do context.SaveChanges(), EF will generate an update statement that will update all the fields of the entity. This is not...

EF Code first - many to many relation mapping table with extra columns

entity-framework,ef-code-first,entity-framework-6,code-first-migrations

I think it'll work if you do the following: Remove the configuration you showed in the code snippet above Add a mapping table and configure its table name to match the original table name. // name this whatever you want class UserUserGroupMapping { public UserUserGroupMappingId { get; set; } public...

IronPython entity framwork 6 Could not find attribute where

.net,linq,entity-framework,entity-framework-6,ironpython

Found the issues; I had to use import: import clr import System clr.ImportExtensions(System.Linq) ...

How to upgrade mvc2 to mvc5?

asp.net-mvc,asp.net-mvc-2,asp.net-mvc-5

I would highly recommend you to create a new empty MVC 5 project, and move all your files there from old MVC 2 project. If you just try to update DLLs its very hard be sure if you updated all DLLs, proj file, nugets, or at least little bit more...

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...

Produce different serialized JSON for a given class in different scenarios

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

I finally went with a mix of Wrapper classes and the methodology suggested by Raphaël Althaus: use Wrappers where some amount of sophistication may be required and use Raphaël's suggestion when simplicity will do. Here's how I am using wrappers (intentionally left out null checks): public class Entity1View1 { protected...

Convert string value to english word

c#,asp.net-mvc-5

First you need to get the decimal part of the number into a separate integer, then just call your number to words function twice something like this: double value = 125.23; int dollars = (int)value; int cents = (int)((value - (int)value) * 100); Console.WriteLine("{0} dollars and {1} cents", wordify(dollars), wordify(cents));...

EPPlus export model to Excel: System.NullReferenceException

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

You can't (well certainly SHOULDN'T) try to save directly to a user's filesytem from a web application. I suspect your null reference is somewhere in the Environment.SpecialFolders... object. It woud be better to return the file as a byte array to the response in your controller action. This way the...

Entity Framework Automatic migration

c#,entity-framework-6

You should be generating scripts from migration to be executed in the production. What works for me is to use Update-Database -Script That creates a script with a 'migration difference', which you can manually apply as an SQL script on the target server database (and you should get the right...

ApplicationUser ICollection member not being saved in DB

c#,.net,entity-framework,asp.net-mvc-4,asp.net-mvc-5

You need to model your collection items. You could go many to many or one to many. // many to many public class Interest { public int InterestId { get; set; } public string InterestDesc { get; set; } // field can't match class name } // one to many...

Web API Basic Auth inside an MVC app with Identity Auth

c#,authentication,asp.net-web-api,asp.net-mvc-5

I us a filter attribute to adorn the actions i wanted to expose to Simple Auth. I cant remember where i got this code from (probably stackoverflow i just don't have the link so i cant claim credit for it) public class BasicHttpAuthorizeAttribute : AuthorizeAttribute { protected override bool IsAuthorized(HttpActionContext...

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');...

In MVC Razor, how can I correctly add querystring parameters to an html.actionlink?

asp.net-mvc,razor,asp.net-mvc-5

The problem arise from the fact that there is no overload as LinkExtensions.ActionLink Method (HtmlHelper, String, String, String, Object) Use the overloaded method LinkExtensions.ActionLink Method (HtmlHelper, String, String, String, Object, Object) @Html.ActionLink((string)item.Student_Name, "Index", "FourCourseAuditDetails", new { filterByStudent = item.Student_Name}, null) Also need to type cast item.Student_Name to string....

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...

MVC: after export to excel, index action result is not getting called

asp.net-mvc-5,export-to-excel

You can't do that I'm afraid, once you have sent the header for the download, you can't then send another set of headers to do the redirect. There is a technique mentioned in this blog post which you can alter to do a redirect when a cookie appears from the...

How to get tables from database first approach without .tt and edmx files?

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

In order to get "Code First from database" install the latest Entity Framework Tools for Visual Studio 2012/2013 (version 6.1.3)

Inherited Property of Model is always returning Null Value

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

You radio button group is not inside the <form> tags so its value is not sent when the form is submitted. You need to move the radio buttons to inside the form (in the partial) and remove the hidden input for property ReportName. If this is not possible you could...

Distribute entity framework models over different assemblies

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

You can search for your models in every assembly over reflection. Iterate through the AppDomain's assemblies and search for an attribute, interface or base class, see an example below. protected override void OnModelCreating(DbModelBuilder modelBuilder) { var entityMethod = typeof(DbModelBuilder).GetMethod("Entity"); foreach (var assembly in AppDomain.CurrentDomain.GetAssemblies()) { var entityTypes = assembly .GetTypes()...

Why is KnockoutJS not showing the same number of objects as my Web API controller?

knockout.js,asp.net-mvc-5,web-api

ko.observableArray does have a length property, but it is the property of the observableArray function itself, not of the array: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function/length To get the length of the enclosed array, invoke observableArray then call length: self.object().length. For example in your code, change your alert to: alert(xhr + " " + status...

Convert SQL to linq statement

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

Just use Any(), which will return a boolean, true if your query returns anything, else false. var result =(from a in _applicationRepository.GetList(a => a.ID == applicationId) from r in _roleRepository.GetList(r => r.ApplicationId == a.ID && r.Name == rolename) from au in _authorizationRepository.GetList(au => au.ApplicationId == a.ID && r.ID == au.RoleId)...

Converting string to datetime in mapping to viewmodel

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

You need to first materialize the query to your application and then parse it. Entity Framework doesn't know how to execute dot Net methods, it only knows how to translate them to SQL

Property Is Required on Update EF6

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

Best workaround I know: entity.Property = "placeholder"; var entry = _context.Entry(entity); entry.State = EntryState.Modified; entry.Property(m => m.Property).IsModified = false; _context.SaveChanges(); You mark entity as modified and then exclude not modified properties. As for validation, you need to set valid value for that field just to pass validation....

Getting users from another AD Domain using PrincipalContext

c#,asp.net,active-directory,asp.net-mvc-5,active-directory-group

You need to use the underlying System.DirectoryServices.DirectoryEntry for the group: var groupEntry = (DirectoryEntry)group.GetUnderlyingObject(); (Note: according to MSDN GetUnderlyingObject() will return a DirectoryEntry, even though the return type is object.) From there you can get the member distinguished names: var memberDistinguishedNames = groupEntry.Properties["member"].Cast<string>(); The users from the other domain are...

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 =...

MVC/Razor: Error at Viewbag.Title

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

Ok, the culprit was this: <ul class="list-inline text-center propertyRegionUL"> <li data-marketid="Miami-Dade" class="regionLI @(ViewContext.RouteData.Values["id"].ToString() == "Miami-Dade" ? "active" : "")">Miami Dade</li> <li data-marketid="Fort-Lauderdale" class="regionLI @(ViewContext.RouteData.Values["id"].ToString() == "Fort-Lauderdale" ? "active" : "")">Fort Lauderdale</li> <li data-marketid="West-Palm-Beach" class="regionLI @(ViewContext.RouteData.Values["id"].ToString() ==...

Embedding a Silverlight App into a MVC

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

Do you have the Silverlight project added to your MVC project? If you don't you will need to go to your project that is your MVC, right click it and go to properties. Go to silverlight applications then add the project there too. Then try it with your current code...

How to get routevalues from URL with htmlhelpers or JavaScript?

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

To write server side code to be processed by razor engine, you have to prepend your statement with @. That will only work if that Javascript is embedded on the view. You can also do it with Javascript. Something like this should do the trick var urlParts = location.href.split('/'); var...

Store does not implement IUserLockoutStore

asp.net-mvc-5,asp.net-identity

See this answer: When implementing your own IUserStore, are the "optional" interfaces on the class actually optional? You will need to trick or override the method you are trying to call in your store to implement one that does not use the "optional" lockout store. You may be unpleasantly surprised...

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 - Validate a specific field on client-side

javascript,jquery,asp.net-mvc,validation,asp.net-mvc-5

After digging around in the source code, I've come to these conclusions. First, the purpose of unobtrusive is to wire up the rules and messages, defined as data- attributes on the form elements by MVC, to jQuery.validation. It's for configuring/wiring up validation, not a complete wrapper around it, so when...

Entity Framework Code First - Optional/required two-way navigation

entity-framework,ef-code-first,foreign-keys,entity-framework-6,foreign-key-relationship

The problem is EF take by convention you want to create an one-to-one relationship, and in case like this you need to specify which entity is the principal. If you want to create an one to one relationship with a different PK in each entity, you can't declare FK properties...

Database object with different data

sql,asp.net,asp.net-mvc,database,entity-framework-6

Ideally what you want is a many-to-many relationship between your Shop and Product entities: public class Shop { public int ShopId {get; set;} public virtual ICollection<ShopProduct> ShopProducts {get; set;} } public class Product { public int ProductId {get; set;} public string Name {get; set;} public virtual ICollection<ShopProduct> ShopProducts {get; set;}...

Need to fetch Oracle RAW in C# string datatype “as is”

c#,oracle,entity-framework-6

The RAW datatype is documented as: The RAW and LONG RAW datatypes are used for data that is not to be interpreted (not converted when moving data between different systems) by Oracle Database. These datatypes are intended for binary data or byte strings. In other words, it's a better mapping...