Help with attribute mapping my class - nhibernate

My class looks like:
public class User
{
public virtual int ID {get;set;}
public virtual string Username {get;set;}
}
Table:
User
-UserID INT NOT NULL,
-Username NVARCHAR(50) NOT NULL
UserID is the PK, IDENTITY.
How would I use nhibernate attribute mapping for my class?

[Class(0, Name = "User", Table = "Users")]
public class User
{
[Id(0, Name = ID", Type = "Int32", Column = "ID")]
[Generator(1, Class = "native")]
public virtual int ID {get;set;}
[Property(0, Name = "Username", Column = "Username", Type = "string", NotNull = true , Length = 50)]
public virtual string Username {get;set;}
}

Related

Using LINQ to combine object and nested collection information into a new object

Using LINQ, is it possible to combine properties from both an object and a nested collection of that object into a new object? So for each item in the nested collection, I want to create a new object that has the nested object information coupled with the parent object's info.
Using a sample scenario, I'm trying to do something like this:
Teachers.Select(Function(item) New TeacherRecord() With
{.TeacherId = item.Id,
.TeacherName = item.Name,
.StudentID = ? ,
.StudentName = ?}).ToList()
Sample Classes
Public Property Teachers as List(of Teacher)
Public Class Teacher
Public Property ID as Integer
Public Property Name as String
Public Property Room as String
Public Property Students as List(of Student)
End class
Public Class Student
Public Property ID as Integer
Public Property Name as String
End Class
Public Class TeacherRecord
Public Property TeacherId as Integer
Public Property TeacherName as String
Public Property StudentId as Integer
Public Property StudentName as String
End Class
You need to use SelectMany, I don't know much about VB but this is how you do it in C#:
List<TeacherRecord> records = teachers.SelectMany(t => t.Students, (t, s) =>
new TeacherRecord { TeacherId = t.ID,
TeacherName = t.Name,
StudentId = s.ID,
StudentName = s.Name }).ToList();
you will need to rethink your TeacherRecord relationship to a Teacher Or Student - now it is unclear, but generally you can combine then for your ViewData and code will look like this:
void Main(){
List<Teacher> teacher = new List<Teacher>();
List<Student> student = new List<Student>();
student.Add(new Student{ID=1,Name="Tom"});
student.Add(new Student{ID=2,Name="Jerry"});
teacher.Add(new Teacher{ID=1
,Name="John"
,Room = "Room A"
,Students = student});
var combined = (from t in teacher
select t).ToList();
}
// Define other methods and classes here
public class Teacher
{
public int ID { get; set; }
public string Name { get; set; }
public string Room { get; set; }
public List<Student> Students { get; set; }
}
public class Student
{
public int ID { get; set; }
public string Name { get; set; }
}
public class TeacherRecord
{
public int TeacherId { get; set; }
public string TeacherName { get; set; }
public int StudentId { get; set; }
public string StudentName { get; set; }
}
and result will be something like this:

Assign permission for pages using Code first in asp.net MVC

Here I have created a Model Structure in asp.net mvc:
public class UserModel
{
public int UserId { get; set; }
public string UserName { get; set; }
public string Password { get; set; }
public List<Permission> Permissions { get; set; }
public string FirstName { get; set; }
public string LastName { get; set; }
}
public class Permission
{
public int PermissionID { get; set; }
public bool IsPermit { get; set; }
public string Name { get; set; }
}
and setting some default values in the list and while I am adding the user in the list I assign the permission for pages to that user through the UI (by checking permission checkboxes), so that user can access only the assigned pages:
public static class Repository
{
public static List<UserModel> GetUsers()
{
List<UserModel> listUsers = new List<UserModel>
{
new UserModel
{
UserId = 1,
UserName = "abc",
Password = "abc",
Permissions = new List<Permission>
{
new Permission
{
PermissionID = 1,
IsPermit = true,
Name = "Page1"
},
new Permission
{
PermissionID = 2,
IsPermit = false,
Name = "Page2"
},
new Permission
{
PermissionID = 3,
IsPermit = false,
Name = "Page3"
},
new Permission
{
PermissionID = 4,
IsPermit = false,
Name = "Page4"
}
},
FirstName = "Rohit",
LastName = "Sharma"
},
new UserModel
{
UserId = 2,
UserName = "xyz",
Password = "xyz",
Permissions = new List<Permission>
{
new Permission
{
PermissionID = 1,
IsPermit = false,
Name = "Page1"
},
new Permission
{
PermissionID = 2,
IsPermit = true,
Name = "Page2"
},
new Permission
{
PermissionID = 3,
IsPermit = true,
Name = "Page3"
},
new Permission
{
PermissionID = 4,
IsPermit = true,
Name = "Page4"
}
},
FirstName = "Rahul",
LastName = "Sharma"
}
};
return listUsers;
}
}
Now I want to do the same by using code first approach of database with the help of DbContext class. I have a static list of page permission in a database table (Id =1, Name=Page1; Id =2, Name=Page2; Id =3, Name=Page3; Id =4, Name=Page4).
I am confused while creating model structure for database. Please guide me how to create model structure and mapping of structure with the tables.
I have a table (Permission) in my database with default rows.
ID Name
1 Page1
2 Page2
3 Page3
4 Page4
Now, when I adding user I assigning permission to that user through static checkboxes (Page1, Page2, Page3 and Page4). That’s why I created static table in a database that contains list of pages. My User table is initially blank.
User
Id int NotNull
UserName nvarchar(100) AllowNull
Password nvarchar(100) AllowNull
FirstName nvarchar(100) AllowNull
LastName nvarchar(100) AllowNull
You can use below mentioned structure when you're using code first.You have to maintain conventions when you're using code first (But can be changed when you're using Fluent API).
Model Classes
public class User
{
public int Id { get; set; }
public string UserName { get; set; }
public string Password { get; set; }
public string FirstName { get; set; }
public string LastName { get; set; }
public virtual ICollection<Permission> Permissions { get; set; }
}
public class Permission
{
public int Id { get; set; }
public bool IsPermit { get; set; }
public string Name { get; set; }
public virtual User { get; set; }
}
Tables (This will auto generate.But If you want you can create manually also)
Users
Id int NotNull
UserName nvarchar(100) AllowNull
Password nvarchar(100) AllowNull
FirstName nvarchar(100) AllowNull
LastName nvarchar(100) AllowNull
Permissions
Id int NotNull
IsPermit bit AllowNull
Name nvarchar(100) AllowNull
User_Id int NotNull
DbContext Derived Class
public class UserEntities : DbContext
{
public DbSet<User> Users { get; set; }
public DbSet<Permission> Permissions { get; set; }
}
Fore more information check Code-First Development with Entity Framework
I hope this will help to you.

Nhibernate projection with child collection

Using NHibernate 2.1, I'm trying to project an entity and its child collection into a DTO. My entity looks like this..
public class Application
{
public int Id {get;set;}
public string Name {get;set;}
public List<ApplicationSetting> Settings {get;set;}
// A bunch of other properties that I don't want in the DTO
}
public class ApplicationSetting
{
public int Id {get;set;}
public string Name {get;set;}
public string Code {get;set;}
// A bunch of other properties that I don't want in the DTO
}
My DTO looks like this..
public ApplicationDto
{
public int Id {get;set;}
public string Name {get;set;}
public List<ApplicationSettingDto> Settings {get;set;}
}
public class ApplicationSettingDto
{
public int Id {get;set;}
public string Name {get;set;}
public string Code {get;set;}
}
My code to select JUST the Application and project it is this (using Nhibernate 2.1 and nhLambdaExtensions)
var applicationAlias = new Application();
var criteria = Session
.Add<Application>(a => a.Id == id);
int? Id = null;
string Name = null;
criteria
.SetProjection
(
Projections.Distinct(
Projections.ProjectionList()
.Add(LambdaProjection.Property<Application>(a => a.Id).As(() => Id))
.Add(LambdaProjection.Property<Application>(a => a.Name).As(() => Name))
)
);
criteria.SetResultTransformer(Transformers.AliasToBean(typeof(ApplicationDto)));
var contract = criteria.UniqueResult<ApplicationDto>();
My question is, how do I project just SOME of the properties from the ApplicationSettings entity to the ApplicationSettingsDto child collection?
I think you might need to do a MutiQuery and bring together the DTO parents and children yourself.

NHibernate - AliasToBean and Associations

I have an entity which looks like this:
public class MyEntity {
public virtual int Id { get; set; }
public virtual string Name { get; set ; }
public virtual Role UserRole { get; set; }
}
The property "Name" is not a mapped property but "Id" and "UserRole" is. I want to populate this class using a custom criteria like this:
ICriteria c = Db.CreateCriteria<MyEntity>("m")
.CreateAlias("Role", "r")
.SetProjection(Projections.ProjectionList()
.Add(
Projections.SqlProjection(#"Name = case TypeId
when 2 then (select Name from tblOne where Id = EntityId)
when 4 then (select Name from tblTwo where Id = EntityId)
when 3 then (select Name from tblThree where Id = EntityId)
end", new string[] { "Name" }, new NHibernate.Type.IType[] { NHibernateUtil.String }))
.Add(Projections.Property("m.Id"), "Id")
.Add(Projections.Property("r.Id"), "UserRole.Id")
.Add(Projections.Property("r.Desc"), "UserRole.Desc")
.Add(Projections.Property("r.Permission"), "UserRole.Permission")
)
.SetResultTransformer(Transformers.AliasToBean<EntityPermission>());
However if I execute this it throws an exception "Could not find a setter for property '{UserRole.Id}' in class 'MyEntity'".
So my question is doesn't aliastobean support associations, and if it does, what's the proper syntax?
You should crate an alias to "UserRole" instead of "Role", since the name of the property is "UserRole", not "Role".

Link two entities based on unique value not ID

I have the following database tables. Primary keys are ID and AnimalType.Type is a unique string.
Animal
- ID
- Name
- TypeID
AnimalType
- ID
- Type [Herbivore, Carnivore]
My classes are as follows.
public class Animal
{
public int ID { get; private set; }
public string Name { get; set; }
public AnimalType Type { get; set; }
}
public class AnimalType
{
private int ID { get; set; }
public string Type { get; set; }
}
How would I get the following code to work in NHibernate so that it references the same AnimalType of Herbivore?
var horse = new Animal() { Name = "Horse", Type = new AnimalType() { "Herbivore" }};
repository.SaveOrUpdate(horse);
var rabbit = new Animal() { Name = "Rabbit", Type = new AnimalType() { "Herbivore" } };
repository.SaveOrUpdate(rabbit);
UPDATE
Be nice if I could get NHibernate to perform this logic: http://andreas.scherbaum.la/blog/archives/11-Avoid-Unique-Key-violation.html
I'd investigate a few options.
1) If the data doesn't change frequently, can you make AnimalType an Enum instead of an Entity Object?
2) Instantiate an object of the Herbivore AnimalType using animalTypeRepository.FindByType("Herbivore") and pass that object into your new Animal.
3) Move the above logic into the animalRepository.SaveOrUpdate(animal) method so that you'd have...
public class AnimalRepository
{
public void SaveOrUpdate(Animal animal)
{
var animalType = animal.Type;
if (animalType.ID == 0)
{
animal.Type = animalTypeRepository.Find(animalType.Type);
}
// save or update animal...
}
}