I am getting a message: Error: Cannot convert from 'Intranet.Models.LoanOrderModification to Intranet.Models.LoanOrder on the line db.LoanOrders.Add(newLoan); from the code below. I created a new model in the class LoanOrders which I named LoanOrderModification , this class also has LoanOrder. What am I missing where the controller is looking for LoanOrder model and not LoanOrderModification model?
[HttpPost]
public ActionResult CreateModifiedLoanOrder(LoanOrderModification newLoanOrder, string submit)
{
try
{
if (ModelState.IsValid)
{
db.LoanOrders.Add(newLoanOrder);
db.SaveChanges();
return RedirectToAction("LoanOrders");
}
}
catch (Exception ex)
{
ModelState.AddModelError("", ex.Message);
}
return View();
}
Model:
namespace Intranet.Models
{
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.ComponentModel.DataAnnotations;
using System.Web.Mvc;
public partial class LoanOrder
{
public int ID { get; set; }
public string Branch { get; set; }
public partial class LoanOrderModification
{
public int ID { get; set; }
public string Purpose { get; set; }
}
Related
I m working on an existing MVC project.When my context class inherited from DBContext everythink is fine but when i changed it to IdentityDbContext i get that error.The error occured in that line :
var makaleler = context.Makale.ToList();
my controller:
using mvcblogdeneme.Models;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
namespace mvcblogdeneme.Controllers
{
public class HomeController : Controller
{
// GET: Home
BlogDatabaseContext context = new BlogDatabaseContext();
public ActionResult Index()
{
return View();
}
public ActionResult CategoryWidgetGetir()
{
var kat = context.Kategori.ToList();
return View(kat);
}
public ActionResult TumMakalelerGetir()
{
var makaleler = context.Makale.ToList();
return View("MakaleListele", makaleler);//makalelistele bi partial view
}
}
}
this is my model:
namespace mvcblogdeneme.Models
{
using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.ComponentModel.DataAnnotations.Schema;
using System.Data.Entity.Spatial;
[Table("Makale")]
public partial class Makale
{
public int Id { get; set; }
[Required]
[StringLength(150)]
public string Baslik { get; set; }
[Required]
public string Icerik { get; set; }
public DateTime YayimTarihi { get; set; }
public int KategoriID { get; set; }
public virtual Kategori Kategori { get; set; }
}
}
If the exception message shows like this and DbContext is being used:
EntityType '[[table name]]' has no key defined. Define the key for
this EntityType.
EntityType: EntitySet '[[entity name]]' is based on type '[[table name]]'
that has no keys defined.
Then definitely you need to use KeyAttribute on Id property to mark it as primary key field inside table model class and problem will solved:
[Table("Makale")]
public partial class Makale
{
// if the ID also set as auto-increment, uncomment DatabaseGenerated attribute given below
// [DatabaseGenerated(DatabaseGeneratedOption.Identity)]
[Key]
public int Id { get; set; }
[Required]
[StringLength(150)]
public string Baslik { get; set; }
[Required]
public string Icerik { get; set; }
public DateTime YayimTarihi { get; set; }
public int KategoriID { get; set; }
public virtual Kategori Kategori { get; set; }
}
However, if the cause is found out coming from IdentityDbContext and EF Code First being used, you need to do these steps (credits to DotNetHaggis):
Create configuration class for IdentityUserLogin & IdentityUserRole:
// taken from /a/20912641
public class IdentityUserLoginConfiguration : EntityTypeConfiguration<IdentityUserLogin>
{
public IdentityUserLoginConfiguration()
{
HasKey(iul => iul.UserId);
}
}
public class IdentityUserRoleConfiguration : EntityTypeConfiguration<IdentityUserRole>
{
public IdentityUserRoleConfiguration()
{
HasKey(iur => iur.RoleId);
}
}
Add those two configurations above inside OnModelCreating method:
protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
modelBuilder.Configurations.Add(new IdentityUserLoginConfiguration());
modelBuilder.Configurations.Add(new IdentityUserRoleConfiguration());
}
At this point, the error should get resolved due to primary key for every identity tables has been set.
Similar issues:
An exception of type 'System.Data.Entity.ModelConfiguration.ModelValidationException' occurred in EntityFramework.dll
Merge MyDbContext with IdentityDbContext
How to pass LINQ data to View. I have used below code but it throwing conversion error.
namespace WebApplication1.DataContext
{
public class Repositary
{
public ProductMaster productMaster { get; set; }
public ProductDetail productDetail { get; set; }
}
}`
Action Method:-
public ActionResult ProductMasterWithDetails()
{
Model1 db=new Model1();
Repositary rep = new Repositary();
var varResult= from pm in db.ProductMasters join pd in db.ProductDetails on pm.ProductId equals pd.ProductId select new { pm.ProductId, pm.ProductName, pd.Price, pd.ManufactureBy };
ViewBag.result = varResult.ToList();
return View();
}
Error: Cannot initialize type 'WebApplication1.DataContext.Repositary'
with a collection initializer because it does not implement
'System.Collections.IEnumerable'
C:\Users\msnsh\onedrive\documents\visual studio
2013\Projects\WebApplication1\WebApplication1\Controllers\ProductController.cs 55 141 WebApplication1
In View:
#foreach (var result in ViewBag.result){
}
I have two model classes as follows.
namespace WebApplication1.DataContext
{
using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.ComponentModel.DataAnnotations.Schema;
using System.Data.Entity.Spatial;
[Table("ProductMaster")]
public partial class ProductMaster
{
public ProductMaster()
{
ProductDetails = new HashSet<ProductDetail>();
}
[Key]
[DatabaseGenerated(DatabaseGeneratedOption.None)]
public int ProductId { get; set; }
[StringLength(50)]
public string ProductName { get; set; }
public virtual ICollection<ProductDetail> ProductDetails { get; set; }
}
}
namespace WebApplication1.DataContext
{
using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.ComponentModel.DataAnnotations.Schema;
using System.Data.Entity.Spatial;
public partial class ProductDetail
{
public int? Price { get; set; }
[StringLength(50)]
public string ManufactureBy { get; set; }
public int? ProductId { get; set; }
[Key]
public int ProdDetailsId { get; set; }
public virtual ProductMaster ProductMaster { get; set; }
}
}
If we have two model classes then how to replace below single Model namespace ?
#model IEnumerable
I cannot create a single class as below, because my model has two classes,
public Class ProductCustomModel
{
public int ProductId { get; set; }
public int ProductName { get; set; }
public int Price { get; set; }
public int ManufactureBy { get; set; }
}
Here is my Model1 Class.
namespace WebApplication1.DataContext
{
using System;
using System.Data.Entity;
using System.ComponentModel.DataAnnotations.Schema;
using System.Linq;
using System.Data.Entity.Spatial;
public partial class Model1 : DbContext
{
public Model1()
: base("name=Model1")
{
}
public virtual DbSet<ProductDetail> ProductDetails { get; set; }
public virtual DbSet<ProductMaster> ProductMasters { get; set; }
protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
modelBuilder.Entity<ProductDetail>()
.Property(e => e.ManufactureBy)
.IsUnicode(false);
modelBuilder.Entity<ProductMaster>()
.Property(e => e.ProductName)
.IsUnicode(false);
}
}
}
If you getdata in varResult than you should try,
In Conroller.
Model1 db=new Model1();
var varResult= (from pm in db.ProductMasters join pd in db.ProductDetails on pm.ProductId equals pd.ProductId select new { pm.ProductId, pm.ProductName, pd.Price, pd.ManufactureBy }).ToList();
return View("path to the view",varResult);
In View
#model ModelName
#foreach (var result in Model){
}
You should need to change the ViewBag to the customModel/Class which will send the List to your view.
Models:
namespace WebApplication1.DataContext
{
public class Repositary
{
public ProductMaster productMaster { get; set; }
public ProductDetail productDetail { get; set; }
}
public Class ProductCustomModel
{
public int ProductId { get; set; }
public int ProductName { get; set; }
public int Price { get; set; }
public int ManufactureBy { get; set; }
}
}
Change your action Method to this:
public ActionResult ProductMasterWithDetails()
{
Model1 db=new Model1();
Repositary rep = new Repositary();
var varResult= from pm in db.ProductMasters join pd in db.ProductDetails on pm.ProductId equals pd.ProductId select new { pm.ProductId, pm.ProductName, pd.Price, pd.ManufactureBy };
//Make your List Here like this and add the values in it.
List<ProductCustomModel> productCustomModelList = new List<ProductCustomModel>();
Foreach(ProductCustomModel item in varResult)
{
ProductCustomModel singleData = new ProductCustomModel();
ProductId = item.ProductId,
ProductName = item.ProductName,
Price = item.Price,
ManufactureBy = item.ManufactureBy
productCustomModelList.Add(singleData);
}
return View(productCustomModelList);
}
In the View(.cshtml)
#model IEnumerable<WebApplication1.DataContext.ProductCustomModel>
#foreach (var result in Model){
//.. operations
}
I have a model class that is below
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Data.Entity;
namespace MyForms.Models
{
public class Master
{
public int ID { get; set; }
public string ModuleName { get; set; }
public int CreatedBy { get; set; }
public DateTime CreatedDate { get; set; }
public int ModifyBy { get; set; }
public DateTime ModifyDate { get; set; }
public Boolean IsActive { get; set; }
public Boolean IsDeleted { get; set; }
// public virtual ICollection<MasterModule> MasterModules { get; set; }
}
Here in this code I am passing the values through views(textboxes). What are my expections
Module Name is entered through text box and when submit button is clicked
CreatedBy contains the ID of the person who create the module(e.g 1. admin 2. manager)
Created date is automatically added as current Date when submit is clicked
ModifyBy contains the ID of the person who modify (edit) the module(e.g 1. admin 2. manager)
ModifyDate is the curent date when the module is edited
when the module is created is activated always sets to be true.
2 to 6 are settled with coding. Now I want to know how can I handle each situation separetaly.
Currently I am adding all the values manually, I mean through the input box and checkboxes
namespace MyForms.Controllers
{
public class MasterController : Controller
{
//
// GET: /Master/
public ActionResult Index()
{
using (MyFormDemoContext context = new MyFormDemoContext())
{
return View(context.MasterForms.ToList());
}
// return View();
}
public ActionResult Create()
{
return View();
}
[HttpPost]
public ActionResult Create(Master master)
{
try
{
using (MyFormDemoContext context = new MyFormDemoContext())
{
context.MasterForms.Add(master);
context.SaveChanges();
}
return RedirectToAction("Index");
}
catch
{
return View();
}
}
}
}
I've been trying to implement a custom version of the new Identity features in ASP.NET 4.5 (Microsoft.AspNet.Identity), using Visual Studio 2013. After many hours of playing around with this, I've simplified my code in an effort to get it running without errors. I've listed my code below. When doing a Local Registration, the database tables are created, but the CreateLocalUser method fails. I'm hoping that someone can help me identify the changes needed.
Models/MembershipModel.cs
using Microsoft.AspNet.Identity;
using Microsoft.AspNet.Identity.EntityFramework;
using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.ComponentModel.DataAnnotations.Schema;
using System.Data.Entity;
using System.Linq;
using System.Web;
namespace thePulse.web.Models
{
public class PulseUser : IUser
{
public PulseUser() { }
public PulseUser(string userName)
{
UserName = userName;
}
[Key]
public string Id { get; set; }
[Required]
[StringLength(20)]
public string UserName { get; set; }
[StringLength(100)]
public string Email { get; set; }
[Column(TypeName = "Date")]
public DateTime? BirthDate { get; set; }
[StringLength(1)]
public string Gender { get; set; }
}
public class PulseUserClaim : IUserClaim
{
public PulseUserClaim() { }
[Key]
public string Key { get; set; }
public string UserId { get; set; }
public string ClaimType { get; set; }
public string ClaimValue { get; set; }
}
public class PulseUserSecret : IUserSecret
{
public PulseUserSecret() { }
public PulseUserSecret(string userName, string secret)
{
UserName = userName;
Secret = secret;
}
[Key]
public string UserName { get; set; }
public string Secret { get; set; }
}
public class PulseUserLogin : IUserLogin
{
public PulseUserLogin() { }
public PulseUserLogin(string userId, string loginProvider, string providerKey)
{
LoginProvider = LoginProvider;
ProviderKey = providerKey;
UserId = userId;
}
[Key, Column(Order = 0)]
public string LoginProvider { get; set; }
[Key, Column(Order = 1)]
public string ProviderKey { get; set; }
public string UserId { get; set; }
}
public class PulseRole : IRole
{
public PulseRole() { }
public PulseRole(string roleId)
{
Id = roleId;
}
[Key]
public string Id { get; set; }
}
public class PulseUserRole : IUserRole
{
public PulseUserRole() { }
[Key, Column(Order = 0)]
public string RoleId { get; set; }
[Key, Column(Order = 1)]
public string UserId { get; set; }
}
public class PulseUserContext : IdentityStoreContext
{
public PulseUserContext(DbContext db) : base(db)
{
Users = new UserStore<PulseUser>(db);
Logins = new UserLoginStore<PulseUserLogin>(db);
Roles = new RoleStore<PulseRole, PulseUserRole>(db);
Secrets = new UserSecretStore<PulseUserSecret>(db);
UserClaims = new UserClaimStore<PulseUserClaim>(db);
}
}
public class PulseDbContext : IdentityDbContext<PulseUser, PulseUserClaim, PulseUserSecret, PulseUserLogin, PulseRole, PulseUserRole>
{
}
}
Changes to Controllers/AccountController.cs
public AccountController()
{
IdentityStore = new IdentityStoreManager(new PulseUserContext(new PulseDbContext()));
AuthenticationManager = new IdentityAuthenticationManager(IdentityStore);
}
//
// POST: /Account/Register
[HttpPost]
[AllowAnonymous]
[ValidateAntiForgeryToken]
public async Task<ActionResult> Register(RegisterViewModel model)
{
if (ModelState.IsValid)
{
try
{
// Create a profile, password, and link the local login before signing in the user
PulseUser user = new PulseUser(model.UserName);
if (await IdentityStore.CreateLocalUser(user, model.Password))
{
await AuthenticationManager.SignIn(HttpContext, user.Id, isPersistent: false);
return RedirectToAction("Index", "Home");
}
else
{
ModelState.AddModelError("", "Failed to register user name: " + model.UserName);
}
}
catch (IdentityException e)
{
ModelState.AddModelError("", e.Message);
}
}
// If we got this far, something failed, redisplay form
return View(model);
}
As I said above, this implementation fails when the CreateLocalUser method fails (Microsoft.AspNet.Identity.EntityFramework). I cannot figure out why.
The issue here is that IdentityStoreManager has strong dependency on the default implementation of identity EF models. For example, the CreateLocalUser method will create UserSecret and UserLogin objects and save them to stores, which won't work if the store is not using the default model type. So if you customize the model type, it won't work smoothly with IdentityStoreManager.
Since you only customize the IUser model, I simplified the code to inherit custom user from default identity user and reuse other models from identity EF models.
using Microsoft.AspNet.Identity;
using Microsoft.AspNet.Identity.EntityFramework;
using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.ComponentModel.DataAnnotations.Schema;
using System.Data.Entity;
using System.Linq;
using System.Web;
namespace WebApplication11.Models
{
public class PulseUser : User
{
public PulseUser() { }
public PulseUser(string userName) : base(userName)
{
}
[StringLength(100)]
public string Email { get; set; }
[Column(TypeName = "Date")]
public DateTime? BirthDate { get; set; }
[StringLength(1)]
public string Gender { get; set; }
}
public class PulseUserContext : IdentityStoreContext
{
public PulseUserContext(DbContext db) : base(db)
{
this.Users = new UserStore<PulseUser>(this.DbContext);
}
}
public class PulseDbContext : IdentityDbContext<PulseUser, UserClaim, UserSecret, UserLogin, Role, UserRole>
{
}
}
The code above should work with preview version of Identity API.
The IdentityStoreManager API in upcoming release is already aware of this issue and changed all the non-EF dependency code into a base class so that you can customize it by inheriting from it. It should solve all the problems here. Thanks.
PulseUser.Id is defined as a string but doesn't appear to be set to a value. Were you meant to be using a GUID for the Id? If so, initialise it in the constructor.
public PulseUser() : this(String.Empty) { }
public PulseUser(string userName)
{
UserName = userName;
Id = Guid.NewGuid().ToString();
}
You will also want to perform a check that the user name doesn't already exist. Look at overriding DbEntityValidationResult in PulseDbContext. Do a new MVC project in VS2013 to see an example.
Since there are alot of changes on this when going to RTM, i have updated the SPA template that uses a WebApi controller for all the identity signin and such. Its a really cool template , if you havent seen it.
I put all my code here:
https://github.com/s093294/aspnet-identity-rtm/tree/master
(Do note, its only for inspiration. I only made it work and nothing more. Properly have a bug or two also).
I am trying to get the Latest News from my database but I keep getting this error: The ObjectContext instance has been disposed and can no longer be used for operations that require a connection. the error happens on the NewsEntity.GetObject() method. I've tried adding the ToList, enabled LazyLoading, re-ordered the way I create the object sets. I have taken out the loading of the Author and Icon and that worked but I need them :) Thanks for any help.
Here is my NewsEntity class:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace Web.Repository.Entity
{
public class NewsEntity : BaseEntity<News>
{
public int Id { get; set; }
public string Title { get; set; }
public string Summary { get; set; }
public string Content { get; set; }
public int Icon { get; set; }
public DateTime Posted { get; set; }
public int Author { get; set; }
public bool Deleted { get; set; }
public virtual MemberEntity AuthorEntity { get; set; }
public virtual IconEntity IconEntity { get; set; }
public override News GetObject()
{
return new News
{
Id = Id,
Title = Title,
Summary = Summary,
Content = Content,
IconId = Icon,
Icon = IconEntity.GetObject(),
Posted = Posted,
AuthorId = Author,
Author = AuthorEntity.GetObject(),
Deleted = Deleted
};
}
}
}
This is my NewsObject class (For data transfer):
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace Web.Repository.Entity
{
public class News : BaseObject
{
public int Id { get; set; }
public string Title { get; set; }
public string Summary { get; set; }
public string Content { get; set; }
public int IconId { get; set; }
public DateTime Posted { get; set; }
public int AuthorId { get; set; }
public bool Deleted { get; set; }
public Member Author { get; set; }
public Icon Icon { get; set; }
}
}
This is my Database Context class:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Data.Objects;
using Web.Repository.Entity;
namespace Web.Repository
{
public class WebModelContext : ObjectContext
{
private IObjectSet<MemberEntity> _members;
private IObjectSet<IconEntity> _icons;
private IObjectSet<NewsEntity> _news;
public WebModelContext()
: base("name=WebRepository", "WebRepository")
{
ContextOptions.LazyLoadingEnabled = true;
_members = CreateObjectSet<MemberEntity>();
_icons = CreateObjectSet<IconEntity>();
_news = CreateObjectSet<NewsEntity>();
}
public IObjectSet<MemberEntity> Members
{
get { return _members; }
}
public IObjectSet<IconEntity> Icons
{
get { return _icons; }
}
public IObjectSet<NewsEntity> News
{
get { return _news; }
}
}
}
This is my NewsRepository class:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Web.Repository.Entity;
namespace Web.Repository
{
public class NewsRepository : IDisposable
{
private WebModelContext _context;
private WebModelContext Context
{
get
{
if (_context == null)
_context = new WebModelContext();
return _context;
}
}
public NewsRepository() { }
public IEnumerable<News> GetLatestNews()
{
return Context.News.Where(news => !news.Deleted).OrderByDescending(news => news.Posted).Take(5).ToList().Select(news => news.GetObject());
}
#region Disposing
private bool disposed;
protected virtual void Dispose(bool disposing)
{
if (!this.disposed)
{
if (disposing && _context != null)
{
_context.Dispose();
}
}
this.disposed = true;
}
public void Dispose()
{
Dispose(true);
GC.SuppressFinalize(this);
}
#endregion
}
}
This is my class to get the latest news:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using Web.Repository.Entity;
using Web.Repository;
namespace Web.Infrastructure
{
public static class NewsHelper
{
public static IEnumerable<News> GetLatestNews()
{
IEnumerable<News> news;
using (var repository = new NewsRepository())
{
news = repository.GetLatestNews();
}
return news;
}
}
}
This is my controller:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using Web.Repository.Entity;
using Web.Models;
using Web.Infrastructure;
namespace Web.Controllers
{
public class HomeController : BaseController
{
public ActionResult Index()
{
NewsListModel model = new NewsListModel { News = NewsHelper.GetLatestNews().ToList() };
return View(model);
}
}
}
and finally this is my model:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using Web.Repository.Entity;
namespace Web.Models
{
public class NewsListModel
{
public IEnumerable<News> News { get; set; }
}
}
I fixed this by ensuring the latest news was infact a list instead of a collection/iqueryable