Deletion issue using fluent nhibernate in mvc 3 - asp.net-mvc-3

I've a layer name MVCTemplate.Common, having two folders Entities and Mappings. In Entities User.cs and Role.cs is as under respectively:
using System;
using System.Collections.Generic;
namespace MVCTemplate.Common.Entities
{
public class User
{
public virtual Guid UserID { get; set; }
public virtual string UserName { get; set; }
public virtual string Password { get; set; }
public virtual string FullName { get; set; }
public virtual string Email { get; set; }
public virtual TimeSpan LastLogin { get; set; }
public virtual bool IsActive { get; set; }
public virtual DateTime CreationDate { get; set; }
public virtual IList<Role> UserInRoles { get; set; }
public User()
{
UserInRoles = new List<Role>();
}
}
}
using System.Collections.Generic;
namespace MVCTemplate.Common.Entities
{
public class Role
{
public virtual int? RoleID { get; set; }
public virtual string RoleName { get; set; }
public virtual bool IsActive { get; set; }
public virtual string Description { get; set; }
public virtual IList<User> Users { get; set; }
//public virtual IList<RolePermission> RolePermission { get; set; }
public Role()
{
Users = new List<User>();
}
public virtual void AddUsers(User _user)
{
_user.UserInRoles.Add(this);
Users.Add(_user);
}
}
}
Now, In Mappings folder their mappings files is as under:
using FluentNHibernate.Mapping;
using MVCTemplate.Common.Entities;
namespace MVCTemplate.Common.Mappings
{
public class RoleMap : ClassMap<Role>
{
public RoleMap()
{
Table("tblRoles");
Id(role => role.RoleID).GeneratedBy.Identity();
Map(role => role.RoleName).Not.Nullable();
Map(role => role.IsActive).Not.Nullable();
Map(role => role.Description).Not.Nullable();
HasManyToMany(role => role.Users).Cascade.All().Table("tblUserInRoles");
//HasMany(role => role.User);
//HasMany(role => role.RolePermission);
}
}
}
using FluentNHibernate.Mapping;
using MVCTemplate.Common.Entities;
namespace MVCTemplate.Common.Mappings
{
public class UserMap : ClassMap<User>
{
public UserMap()
{
Table("tblUsers");
Id(user => user.UserID).GeneratedBy.Guid();
Map(user => user.UserName).Not.Nullable();
Map(user => user.Password).Not.Nullable();
Map(user => user.FullName).Not.Nullable();
Map(user => user.Email).Not.Nullable();
//Map(user => user.LastLogin).Nullable();
Map(user => user.IsActive).Not.Nullable();
Map(user => user.CreationDate).Not.Nullable();
HasManyToMany(user => user.UserInRoles).Cascade.All().Table("tblUserInRoles");
//HasMany(user => user.UserInRoles);
}
}
}
Now, from controller, I got specific user object in user object and now want to delete it, the simple code is as under:
using System;
using System.Collections.Generic;
using System.Web.Mvc;
using MVCTemplate.BussinessLayer.Facade;
using MVCTemplate.Common.Entities;
namespace MVCTemplate.Web.Controllers
{
public class HomeController : Controller
{
private UserManagement _userManagement;
public ActionResult Index()
{
ViewBag.Message = "Welcome to ASP.NET MVC!";
_userManagement = new UserManagement();
var oUser = _userManagement.GetUserBy(new Guid("4fb5856a-58d9-4b78-8d08-bce645bc93c7"));
oUser.UserInRoles = new List<Role>();
_userManagement.Delete(oUser);
return View();
}
public ActionResult About()
{
return View();
}
}
}
Now, I just want to delete that user as this user is not exist in any role and there is no entry of it in its junction table(UserInRole). I initialize its Role collection to empty for Count=0, but after calling deleting method it throw an error with sqlQuery which is as under:
could not delete collection: [MVCTemplate.Common.Entities.User.UserInRoles#4fb5856a-58d9-4b78-8d08-bce645bc93c7][SQL: DELETE FROM tblUserInRoles WHERE User_id = #p0]
Note that in Junction table tblUserInRole there no field of that name User_id as mentioned in error, due to which in the inner exception it is telling that column name User_id not exist. But in junction table I have only two field 1) UserID and 2) RoleID.
Any suggestion how to resolve it?

looks like a mapping error to me. Change:
HasManyToMany(user => user.UserInRoles).Cascade.All().Table("tblUserInRoles");
To
HasManyToMany(user => user.UserInRoles)
.Cascade.All()
.Table("tblUserInRoles")
.ParentKeyColumn("UserID")
.ChildKeyColumn("RoleID");

Related

Automapper one to one mapping

I have working solution, but a bit doubt if I made it correctly. I have base class from which derive 3 other classes Ad:
public class Ad
{
public int Id { get; set; }
public string Title { get; set; }
public Address Address { get; set; }
}
My Address class look like this:
public class Address
{
[ForeignKey("Ad")]
public int AddressId { get; set; }
public string Street { get; set; }
public string City { get; set; }
public string ZipCode { get; set; }
public virtual Ad Ad { get; set; }
}
Now I'm using automapper with this mapping:
Mapper.Initialize(config =>
{
config.CreateMap<Auto, AutoViewModel>()
.ForMember(m => m.City, vm => vm.MapFrom(m => m.Address.City))
.ForMember(m => m.Street, vm => vm.MapFrom(m => m.Address.Street))
.ForMember(m => m.ZipCode, vm => vm.MapFrom(m => m.Address.ZipCode)).ReverseMap();
});
Where AutoViewModel looks like this:
public class AutoViewModel
{
public int Id { get; set; }
public string Title { get; set; }
public string Street { get; set; }
public string City { get; set; }
public string ZipCode { get; set; }
}
In my Create and Edit actions I use this binding:
[HttpPost]
[ValidateAntiForgeryToken]
public async Task<IActionResult> Edit(int id, AutoViewModel vm)
{
Address address = new Address();
address.AddressId = vm.Id;
address.City = vm.City;
address.Street = vm.Street;
address.ZipCode = vm.ZipCode;
var auto = Mapper.Map<Auto>(vm);
auto.Address = address;
if (id != auto.Id)
{
return NotFound();
}
if (ModelState.IsValid)
{
try
{
_context.Update(auto);
await _context.SaveChangesAsync();
}
catch (DbUpdateConcurrencyException)
{
if (!AutoExists(auto.Id))
{
return NotFound();
}
else
{
throw;
}
}
return RedirectToAction("Index");
}
return View(auto);
}
Is this way correct? Is there elegant way to do it? I had to specify AddressId explicit because otherwise I'm getting duplicate Foreign key error message...

Multiple Parent models for a child model

I'm creating an MVC3 asp.net application using Entity Framework 4 and C#.
I've tried to read up on EF and model binding, lazy loading, etc. But I've hit an obstacle.
I have a User Model. The Store and UserType models can have an ICollection of Users. When I add a User with the Create Action, How do I specify multiple parents?
I think that I only know how to add if there is one parent.
My Models:
public class UserType
{
public virtual int ID { get; set; }
public virtual string UserTypeName { get; set; }
public virtual ICollection<User> Users { get; set; }
}
public class Store
{
public virtual int ID { get; set; }
public virtual string StoreName { get; set; }
public virtual Address StoreAddress { get; set; }
public virtual ICollection<Workroom> Workrooms { get; set;}
public virtual ICollection<User> Users { get; set; }
}
public class User
{
public virtual int ID { get; set; }
public virtual string Username { get; set; }
public virtual string Email { get; set; }
public virtual Store Store { get; set; }
public virtual UserType UserType { get; set; }
}
Here is my db context:
public DbSet<Workroom> Workrooms { get; set; }
public DbSet<Ticket> Tickets { get; set; }
public DbSet<Customer> Customers { get; set; }
public DbSet<Store> Stores { get; set; }
public DbSet<User> Users { get; set; }
public DbSet<UserType> UserTypes { get; set; }
protected override void OnModelCreating(ModelBuilder modelBuilder)
{
modelBuilder.Entity<Store>()
.HasMany(store => store.Workrooms)
.WithRequired(workroom => workroom.Store);
modelBuilder.Entity<Store>()
.HasMany(store => store.Users)
.WithRequired(user => user.Store);
modelBuilder.Entity<UserType>()
.HasMany(usertype => usertype.Users)
.WithRequired(user => user.UserType);
base.OnModelCreating(modelBuilder);
}
Here's my create action:
public ActionResult Create()
{
return View(new User());
}
//
// POST: /Users/Create
[HttpPost]
public ActionResult Create(User newUser)
{
try
{
int storeID = newUser.Store.ID;
var store = _db.Stores.Single(r => r.ID == storeID);
store.Users.Add(newUser);
_db.SaveChanges();
return RedirectToAction("Index");
}
catch (Exception ex)
{
ModelState.AddModelError("", ex.InnerException.Message);
return View();
}
}
Do I just add another "Add" call for UserType? for example:
int userTypeID = newUser.UserType.ID
var usertype = _db.UserTypes.Single(s => s.ID == userTypeID)
How would the Entity Framework know that Users has another Parent??? ...do I care?
My hunch is that I should be doing this a different way, more specific and more accurate.
In this case, you probably want to add the user to the Users table, rather than the Stores. Then you assign the StoreID and UserTypeID to the user before you commit.
It looks like you're already setting the StoreID in your UI, are you doing the same for UserType? If so, then just add the user to the users table and you should be good.

cant insert complex object to database using entity frame work

I am developing an asp.net mvc application, which has these enity classes:
public class Person
{
public int PersonID { get; set; }
public string PersonPicAddress { get; set; }
public virtual List<Person_Local> PersonLocal { get; set; }
}
public class Person_Local
{
public int PersonID { get; set; }
public int CultureID { get; set; }
public string PersonName { get; set; }
public string PersonFamily { get; set; }
public string PersonAbout { get; set; }
public virtual Culture Culture { get; set; }
public virtual Person Person { get; set; }
}
public class Culture
{
public int CultureID { get; set; }
[Required()]
public string CultureName { get; set; }
[Required()]
public string CultureDisplay { get; set; }
public virtual List<HomePage> HomePage { get; set; }
public virtual List<Person_Local> PersonLocak { get; set; }
}
I defined an action with [Httppost] attribute, which accepts complex object from a view.
Here is the action :
[HttpPost]
public ActionResult CreatePerson([Bind(Prefix = "Person")]Person obj)
{
AppDbContext da = new AppDbContext();
//Only getting first PersonLocal from list of PersonLocals
obj.PersonLocal[0].Person = obj;
da.Persons.Add(obj);
da.SaveChanges();
return Jsono(...);
}
But when it throws error as below :
Exception:Thrown: "Invalid column name 'Culture_CultureID'." (System.Data.SqlClient.SqlException)
A System.Data.SqlClient.SqlException was thrown: "Invalid column name 'Culture_CultureID'."
And the insert statement :
ADO.NET:Execute Reader "insert [dbo].[Person_Local]([PersonID], [PersonName], [PersonFamily], [PersonAbout], [Culture_CultureID])
values (#0, #1, #2, #3, null)
select [CultureID]
from [dbo].[Person_Local]
where ##ROWCOUNT > 0 and [CultureID] = scope_identity()"
The command text "insert [dbo].[Person_Local]([PersonID], [PersonName], [PersonFamily], [PersonAbout], [Culture_CultureID])
values (#0, #1, #2, #3, null)
select [CultureID]
from [dbo].[Person_Local]
where ##ROWCOUNT > 0 and [CultureID] = scope_identity()" was executed on connection "Data Source=bab-pc;Initial Catalog=MainDB;Integrated Security=True;Application Name=EntityFrameworkMUE", building a SqlDataReader.
Where is the problem?
Edited:
Included EntityConfigurations Code:
public class CultureConfig : EntityTypeConfiguration<Culture>
{
public CultureConfig()
{
HasKey(x => x.CultureID);
Property(x => x.CultureName);
Property(x => x.CultureDisplay);
ToTable("Culture");
}
}
public class PersonConfig : EntityTypeConfiguration<Person>
{
public PersonConfig()
{
HasKey(x => x.PersonID);
Property(x=>x.PersonPicAddress);
ToTable("Person");
}
}
public class Person_LocalConfig : EntityTypeConfiguration<Person_Local>
{
public Person_LocalConfig()
{
HasKey(x => x.PersonID);
HasKey(x => x.CultureID);
Property(x=>x.PersonName);
Property(x => x.PersonFamily);
Property(x => x.PersonAbout);
ToTable("Person_Local");
}
}
Try to remove fields CultureID and PersonID from Person_Local class. Because you already has field Person and Culture
It looks like your schema is out of sync with your model. Make sure you understand EF Code first schema update features, which are described in this blog. If you need more sophisticated schema migration, there are some other approaches in answers to this question.

Fluent NHibernate - Error with HasMany in new version

I Upgrade my NHibernate for 3.1.0.4000 and Fluent for 1.2.0.712 and have some problems with HasMany...
my entities:
public class MateriaPrima
{
public virtual int Id { get; set; }
public virtual string Description { get; set; }
public virtual DateTime Date { get; set; }
public virtual decimal Price { get; set; }
}
public class Product
{
public virtual int Id { get; set; }
public virtual IList<ProductMateriaPrima> ListMateriaPrima { get; set; }
public virtual string Description { get; set; }
public virtual decimal Price { get; set; }
public virtual DateTime Date { get; set; }
public Product()
{
this.ListaMateriaPrima = new List<ProductMateriaPrima>();
}
}
public class ProductMateriaPrima
{
public virtual int Id { get; set; }
public virtual Product Product {get;set;}
public virtual MateriaPrima MateriaPrima { get; set; }
public virtual decimal PrecoCusto {get;set;}
}
And Maps:
public class MateriaPrimaMap : ClassMap<MateriaPrima>
{
public MateriaPrimaMap()
{
Id(m => m.Id).Length(11).Not.Nullable();
Map(m => m.Description).Length(90).Not.Nullable();
Map(m => m.Date).Not.Nullable();
Map(m => m.Price).Not.Nullable();
}
}
public class ProductMateriaPrimaMap : ClassMap<ProductoMateriaPrima>
{
public ProductMateriaPrimaMap()
{
Id(c => c.Id).Length(11);
Map(c => c.Price).Not.Nullable();
References(c => c.MateriaPrima).Column("IdMateriaPrima").Not.LazyLoad();
References(c => c.Product).Column("IdProduct").Not.LazyLoad();
}
}
public class ProdutoMap : ClassMap<Produto>
{
public ProdutoMap()
{
Id(m => m.Id).Length(11).Not.Nullable();
Map(m => m.Description).Length(90).Not.Nullable();
Map(m => m.Price).Length(10);
Map(m => m.Date).Length(12);
Map(m => m.Active).Not.Nullable();
HasMany(x => x.ListaMateriaPrima)
.Table("ProdutoMateriaPrima")
.KeyColumn("IdProduto")
.KeyColumn("IdMateriaPrima")
.Inverse()
.Cascade.AllDeleteOrphan();
}
}
When i try to search, i got the error: {"Unknown column 'listamater0_.MateriaPrima_id' in 'field list'"}
This error don´t happen when i had the old version of Nhibernate and Fluent...
Someone know what´s happening?
Thanks for the help...
This error happend because you didn't set collumn name of Id property, default pattern for id is: entityname_id.
And now in ProductMateriaPrimaMap class you wrote:
References(c => c.MateriaPrima).Column("IdMateriaPrima")
This mean that in you MateriaPrimaMap class you should have Id with collumn name: IdMateriaPrima, but default you have name: MateriaPrima_Id.
I can't say where the problem is exactly because you didn't show the query. But i know that this error happend when Id column name is diffrent from Reference column name.

Fluent Nhibernate & Linq (Property Not Found)

I'm trying to get a web app working based on the S#arp Architecture. At the moment I have a the below code for my entity.
[Serializable]
public abstract class EventBase : Entity
{
#region Properties
[DomainSignature]
public virtual string Name { get; set; }
public virtual string Description { get; set; }
public virtual AgeRange Ages { get; set; }
public virtual int Rating { get; set; }
public virtual decimal Price { get; set; }
public virtual string PhoneNumber { get; set; }
public virtual string EmailAddress { get; set; }
public virtual string Website { get; set; }
public virtual EventState State { get; set; }
#endregion
protected EventBase() {}
protected EventBase(string name, string description)
{
// ReSharper disable DoNotCallOverridableMethodsInConstructor
Name = name;
Description = description;
Price = 0;
State = EventState.New;
// ReSharper restore DoNotCallOverridableMethodsInConstructor
}
}
This is mapped using Fluent NHibernate as follows
public class EventBaseMap : AutoMap<EventBase>
{
public EventBaseMap()
{
Id(x => x.ID).WithUnsavedValue(-1).GeneratedBy.Identity();
Component<AgeRange>(x => x.Ages, m =>
{
m.Map(x => x.From).TheColumnNameIs("AgeFrom");
m.Map(x => x.To).TheColumnNameIs("AgeTo");
});
JoinedSubClass<Music>("EventId", sub =>
{
sub.Map(x => x.Headliner);
});
}
}
I created a very simple repository using the very useful S#arp base repository classes.
public interface IEventRepository : INHibernateRepositoryWithTypedId<EventBase, int>
{
List<EventBase> FindByName(string searchPhase);
}
public class EventRepository : NHibernateRepository<EventBase>, IEventRepository
{
public List<EventBase> FindByName(string searchPhase)
{
return Session.Linq<EventBase>().Where(x => x.Name == searchPhase).ToList();
}
}
I can create entities in the db and return all records. When I try to test the FindByName method I get the below error.
NHibernate.QueryException: could not
resolve property: Name of:
Model.Events.EventBase
Does anyone have any ideas? Is it a problem with my mapping?
Thanks,
This is using the Auto-mapping feature. I thought you only explicitly map properties that you want to override or that don't meet the conventions?
If I add an explicit mapping this solves the issue but I am still not sure why.

Resources