Dapper Dommel - query join automatic mapping - c#

I'm sorry for my bad english, but here it goes, I am using Dapper with Dapper Dommel to simplify operations like crud, but in Dommel's Github says that it supports Join operations too, so I'm trying to implement it on my code, so far I managed to return a simple entity with Get.
But when I am trying to use it for more complex operations like join, it raises an exception.
The error message says: SqlException: Need declare the scalar variable "#product_id".
But in single Get< T > it works.
Packages:
Dapper
Dommel
Dapper-FluentMap.Dommel
Dapper-FluentMap
GitHub Dommel
https://github.com/henkmollema/Dommel
Does someone managed to use Dapper Dommel to return multiple entities in join queries with automatic mapping ?
public class DbContext : IDisposable
{
public SqlConnection Connection { get; private set; }
public DbContext()
{
Connection = new SqlConnection("Server=localhost;Database=BikeStores;Trusted_Connection=True;");
OpenConnection();
}
private bool OpenConnection()
{
try
{
if (Connection.State != System.Data.ConnectionState.Open)
Connection.Open();
return true;
}
catch (Exception ex)
{
Debug.WriteLine(ex.Message);
return false;
}
}
public void Dispose() => Connection.Close();
}
Dommel fluent map:
public class ProductMap : DommelEntityMap<Product>
{
public ProductMap()
{
ToTable("production.products");
Map(m => m.Id)
.ToColumn("product_id")
.IsKey()
.IsIdentity();
Map(m => m.Name)
.ToColumn("product_name");
Map(m => m.BrandId)
.ToColumn("brand_id");
Map(p => p.CategoryId)
.ToColumn("category_id");
Map(p => p.ModelYear)
.ToColumn("model_year");
Map(p => p.ListPrice)
.ToColumn("list_price");
}
}
Category mapping:
public class CategoryMap : DommelEntityMap<Category>
{
public CategoryMap()
{
ToTable("production.categories");
Map(m => m.Id)
.ToColumn("category_id")
.IsKey()
.IsIdentity();
Map(m => m.Name)
.ToColumn("category_name");
}
}
Register mappings:
public RegisterMappings()
{
FluentMapper.Initialize(config =>
{
config.AddMap(new ProductMap());
config.AddMap(new CategoryMap());
config.ForDommel();
});
}
Model:
public class Product
{
public int Id { get; set; }
public string Name { get; set; }
public int BrandId { get; set; }
public int CategoryId { get; set; }
public Category Category { get; set; }
public int ModelYear { get; set; }
public decimal ListPrice { get; set; }
}
Get simple that works:
using (var connect = new DbContext())
{
var product = connect.Connection.Get<Product>(id);
return product;
}
Get Doesn't work:
using (var connect = new DbContext())
{
var prod = connect.Connection.Get<Product, Category, Product>(1, (product, category) =>
{
product.Category = category;
return product;
});
return prod;
}

Related

HttpPost with Many to Many Relationship and Automapper

I´m working on a database with movies and genres (Many to Many). I have created an API and I´m struggling with the DTO's and the Many to Many relationship.
public class MovieDto
{
public int Id { get; set; }
public string Name { get; set; }
public string OriginalTitel { get; set; }
public DateTime ReleseDate { get; set; }
public int Duration { get; set; }
public string Description { get; set; }
public int? Rating { get; set; }
public int? PersonalRating { get; set; }
public int AgeRestrictionId { get; set; }
public ICollection<GenreDto> Genres { get; set; }
}
public class GenreDto
{
public int Id { get; set; }
public string Name { get; set; }
public bool IsChecked { get; set; }
}
With the help of another Post, I have created this Mapping
public MappingProfile()
{
Mapper.CreateMap<Movie, MovieDto>();
Mapper.CreateMap<Genre, GenreDto>()
.ForMember(d => d.Id, opt => opt.MapFrom(s => s.Id))
.ForMember(d => d.Name, opt => opt.MapFrom(s => s.Name));
Mapper.CreateMap<MovieDto, Movie>()
.AfterMap((s, d) =>
{
foreach (var Genre in d.Genres)
Genre.Id = s.Id;
});
Mapper.CreateMap<GenreDto, Movie>()
.ForMember(d => d.Id, opt => opt.MapFrom(s => s.Id));
}
And this is my API Controller
public class MoviesController : ApiController
{
private ApplicationDbContext _context;
public MoviesController()
{
_context = new ApplicationDbContext();
}
// GET /api/movies
public IHttpActionResult GetMovies()
{
return Ok(_context.Movies.ToList().Select(Mapper.Map<Movie, MovieDto>));
}
//GET /api/movies/1
public IHttpActionResult GetMovie(int id)
{
var movie = _context.Movies.SingleOrDefault(m => m.Id == id);
if (movie == null)
return NotFound();
return Ok(Mapper.Map<Movie, MovieDto>(movie));
}
//POST /api/movies
[HttpPost]
public IHttpActionResult CreateMovie (MovieDto movieDto)
{
if (!ModelState.IsValid)
return BadRequest();
var movie = Mapper.Map<Movie>(movieDto);
_context.Movies.Add(movie);
_context.SaveChanges();
return Created(new Uri(Request.RequestUri + "/" + movie.Id), movieDto);
}
//PUT /api/movies/1
[HttpPut]
public void UpdateMovie(int id, MovieDto movieDto)
{
if (!ModelState.IsValid)
throw new HttpResponseException(HttpStatusCode.BadRequest);
var movieInDb = _context.Movies.SingleOrDefault(m => m.Id == id);
if (movieInDb == null)
throw new HttpResponseException(HttpStatusCode.NotFound);
Mapper.Map(movieDto, movieInDb);
_context.SaveChanges();
}
//DELETE api/movies/1
[HttpDelete]
public void DeleteMovie(int id)
{
var movieInDb = _context.Movies.SingleOrDefault(m => m.Id == id);
if (movieInDb == null)
throw new HttpResponseException(HttpStatusCode.NotFound);
_context.Movies.Remove(movieInDb);
_context.SaveChanges();
}
}
If I check the functionality with Postman, I can get the Data from the Database but if I try to Post something I get an error. The reason is the Genre but I don´t know if my mapping is wrong or if I need a kind of connection to my viewModel for the combination of the Movie and the Genre.
I tried a lot of things but I don´t really understand how to go with an API, Many to Many, Dtos, viewModel and Automapper. Can somebody give me an example and an explanation?
Thanks a lot!

Entity Framework trying to insert existing records into database

I have two entities Result and Rule. Result contains a Rule. I fetch a Rule from the database and try to assign it to multiple Result objects, using a different context.
When I try to do context.SaveChanges(), Entity Framework tries to insert the Rule - that already exists - into the database again. I've tried different combinations of attaching and changing state for the past few hours and I'm at a loss.
What could be causing this behavior?
Entities:
public class Result
{
public int Id { get; set; }
public int RuleId { get; set; }
public Rule Rule { get; set; }
}
public class Rule
{
public Rule()
{
Results = new HashSet<Result>();
}
public int Id { get; set; }
public string Identifier { get; set; }
public ICollection<Result> Results { get; set; }
}
Mappings:
public class ResultMapping : EntityTypeConfiguration<Result>
{
public ResultMapping()
{
ToTable("Result");
HasKey(x => x.Id);
HasRequired(x => x.Rule)
.WithMany(y => y.Results)
.HasForeignKey(x => x.RuleId);
}
}
public class RuleMapping : EntityTypeConfiguration<Rule>
{
public RuleMapping()
{
ToTable("Rule");
HasKey(x => x.Id);
Property(x => x.Id).HasDatabaseGeneratedOption(DatabaseGeneratedOption.Identity);
}
}
Assignment:
private void DoStuff(ICollection<Result> results, ScanResultContext context)
{
foreach (var result in results)
{
var rule = RulesFromAnotherContextDictonary[result.Rule.Identifier];
// None of this makes it work
context.Set<Rule>().Attach(rule);
result.Rule = null;
result.RuleId = rule.Id;
context.Set<Result>().Add(result);
}
context.SaveChanges();
}
Attempt 2:
private void DoStuff(ICollection<Result> results, ScanResultContext context)
{
foreach (var result in results)
{
var rule = RulesFromAnotherContextDictonary[result.Rule.Identifier];
// None of this makes it work
context.Set<Rule>().Attach(rule);
result.Rule = rule;
context.Set<Result>().Add(result);
}
context.SaveChanges();
}
Attempt 3:
private void DoStuff(ICollection<Result> results, ScanResultContext context)
{
foreach (var result in results)
{
var rule = context.Set<Rule>().FirstOrDefault(x => x.Identifier == result.Rule.Identifier);
if (rule != null)
result.Rule = rule;
context.Set<Result>().Add(result);
}
context.SaveChanges();
}

Mimicking an Enum List in Entity Framework using code first and DDD

I'm trying to implement an Enum list based on the idea from this answer. My goal is to be able to use an Enum inside my Domain, and have it converted to a class instance when saving and retrieving it from the database.
Using the code as it is (source below), I get a DbUpdateException with the message:
Violation of PRIMARY KEY constraint 'PK_dbo.Faculty'. Cannot insert duplicate key in object 'dbo.Faculty'. The duplicate key value is (0).
The statement has been terminated.
Which is expected, since I'm newing up every instance of Faculty.
To fix it, I tried the solutions from a
few
questions
on
this,
with no success. They suggested to either attach the entity or to set it's state to Unchanged. So I tried overriding SaveChanges() and use:
ChangeTracker.Entries<Faculty>().ToList().ForEach(x => x.State = EntityState.Unchanged);
and
ChangeTracker.Entries<Faculty>().ToList()
.ForEach(x => Entry(x.Entity).State = EntityState.Unchanged);
and even
ChangeTracker.Entries<Department>().ToList().ForEach(department =>
{
foreach (var faculty in department.Entity.Faculties)
{
Entry(faculty).State = EntityState.Unchanged;
}
});
But all of them throw an InvalidOperationException with the message:
Additional information: Saving or accepting changes failed because more than one entity of type 'TestEnum.Entities.Faculty' have the same primary key value. Ensure that explicitly set primary key values are unique. Ensure that database-generated primary keys are configured correctly in the database and in the Entity Framework model. Use the Entity Designer for Database First/Model First configuration. Use the 'HasDatabaseGeneratedOption" fluent API or 'DatabaseGeneratedAttribute' for Code First configuration.
How can I instruct EF to not try and insert these into the database? I need this implementation to work inside SaveChanges() as I'm following DDD design rules and keeping Infrastructure separated from Domain logic.
The code is as follows:
class Program
{
static void Main(string[] args)
{
using (var dbContext = new MyContext())
{
var example = new Department();
example.AddFaculty(FacultyEnum.Eng);
example.AddFaculty(FacultyEnum.Math);
dbContext.Department.Add(example);
var example2 = new Department();
example2.AddFaculty(FacultyEnum.Math);
dbContext.Department.Add(example2);
dbContext.SaveChanges();
var exampleFromDb1 = dbContext.Department.Find(1);
var exampleFromDb2 = dbContext.Department.Find(2);
}
}
}
public enum FacultyEnum
{
[Description("English")]
Eng,
[Description("Mathematics")]
Math,
[Description("Economy")]
Eco,
}
public class Department
{
public int Id { get; set; }
public virtual ICollection<Faculty> Faculties { get; set; }
public Department()
{
Faculties = new List<Faculty>();
}
public void AddFaculty(FacultyEnum faculty)
{
Faculties.Add(faculty);
}
}
public class Faculty
{
public int Id { get; set; }
public string Name { get; set; }
public string Description { get; set; }
private Faculty(FacultyEnum #enum)
{
Id = (int)#enum;
Name = #enum.ToString();
Description = #enum.GetEnumDescription();
}
protected Faculty() { } //For EF
public static implicit operator Faculty(FacultyEnum #enum) => new Faculty(#enum);
public static implicit operator FacultyEnum(Faculty faculty) => (FacultyEnum)faculty.Id;
}
public class MyContext : DbContext
{
public DbSet<Department> Department { get; set; }
public DbSet<Faculty> Faculty { get; set; }
public MyContext()
: base(nameOrConnectionString: GetConnectionString())
{
Database.SetInitializer(new MyDbInitializer());
}
public int SaveSeed()
{
return base.SaveChanges();
}
protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
modelBuilder.Conventions.Remove<PluralizingTableNameConvention>();
modelBuilder.Conventions.Remove<OneToManyCascadeDeleteConvention>();
modelBuilder.Conventions.Remove<ManyToManyCascadeDeleteConvention>();
modelBuilder.Properties<string>()
.Configure(p => p.HasMaxLength(100));
modelBuilder.Configurations.Add(new DepartmentConfiguration());
modelBuilder.Configurations.Add(new FacultyConfiguration());
base.OnModelCreating(modelBuilder);
}
private static string GetConnectionString()
{
return #"Data Source=(localdb)\MSSQLLocalDB;Initial Catalog=TestEnum;Integrated Security=True;Connect Timeout=30;Encrypt=False;TrustServerCertificate=True;ApplicationIntent=ReadWrite;MultiSubnetFailover=False;MultipleActiveResultSets=true;";
}
}
public class MyDbInitializer : DropCreateDatabaseIfModelChanges<MyContext>
{
protected override void Seed(MyContext context)
{
context.Faculty.SeedEnumValues<Faculty, FacultyEnum>(#enum => #enum);
context.SaveSeed();
}
}
public class DepartmentConfiguration : EntityTypeConfiguration<Department>
{
public DepartmentConfiguration()
{
HasMany(x => x.Faculties)
.WithMany();
}
}
public class FacultyConfiguration : EntityTypeConfiguration<Faculty>
{
public FacultyConfiguration()
{
Property(x => x.Id)
.HasDatabaseGeneratedOption(DatabaseGeneratedOption.None);
}
}
public static class Extensions
{
public static string GetEnumDescription<TEnum>(this TEnum item)
=> item.GetType()
.GetField(item.ToString())
.GetCustomAttributes(typeof(DescriptionAttribute), false)
.Cast<DescriptionAttribute>()
.FirstOrDefault()?.Description ?? string.Empty;
public static void SeedEnumValues<T, TEnum>(this IDbSet<T> dbSet, Func<TEnum, T> converter)
where T : class => Enum.GetValues(typeof(TEnum))
.Cast<object>()
.Select(value => converter((TEnum)value))
.ToList()
.ForEach(instance => dbSet.AddOrUpdate(instance));
}
When we use a new instance of a class, EF will always try to insert it into the DB. One way to get around this is by "undoing" what is stored inside the ChangeTracker so it only uses entities loaded from the DB.
So what I did was override the SaveChanges() method, loop through each Department inside ChangeTracker, grab a list of faculty Ids of each, clear the ChangeTracker entries for all Faculty objects and then add them again to their departments, but now using the entities found in either ChangeTracker or through Find().
It looked a bit inefficient, so I ran a test, one using this method and another loading each Faculty from the Db on each run. I ran it 10,000 times, the results are an average of three runs:
Enum list: 77642 ms
Normal class: 70619 ms
As you can see, there's about 10% of speed penalty for using this method, so it's up to you to decide the cost/benefit for your application. To me, the added expressiveness compensates the cost, since my application won't get anywhere near that many operations.
Besides MyContext, some other classes changed from the original post, and I also expanded the console test to cover all use cases, so I'm posting the full solution below.
class Program
{
static void Main(string[] args)
{
var id = 0;
using (var dbContext = new MyContext())
{
var department = new Department();
department.AddFaculty(FacultyEnum.Eng);
department.AddFaculty(FacultyEnum.Math);
dbContext.Department.Add(department);
var department2 = new Department();
department2.AddFaculty(FacultyEnum.Math);
dbContext.Department.Add(department2);
dbContext.SaveChanges();
id = department.Id;
}
using (var dbContext = new MyContext())
{
var department = dbContext.Department.Find(id);
department.AddFaculty(FacultyEnum.Eco);
dbContext.SaveChanges();
}
using (var dbContext = new MyContext())
{
var department = dbContext.Department.Find(id);
var faculty = department.Faculties.Where(x => x.Id == (int)FacultyEnum.Eng).FirstOrDefault();
department.Faculties.Remove(faculty);
dbContext.SaveChanges();
}
using (var dbContext = new MyContext())
{
var department = dbContext.Department.Find(id);
Console.WriteLine($"Department Id {department.Id} has these faculties:");
foreach (var faculty in department.Faculties)
{
Console.WriteLine($"- {faculty.Id}");
}
}
Console.ReadKey();
}
}
public class MyContext : DbContext
{
public DbSet<Department> Department { get; set; }
public DbSet<Faculty> Faculty { get; set; }
public MyContext()
: base(nameOrConnectionString: GetConnectionString())
{
Database.SetInitializer(new MyDbInitializer());
}
public override int SaveChanges()
{
CleanUpFaculties();
return base.SaveChanges();
}
private void CleanUpFaculties()
{
var departments = ChangeTracker
.Entries<Department>()
.Select(x => x.Entity)
.ToList();
var cachedDataToReload = departments
.Select(department => new
{
Department = department,
FacultyIds = department.Faculties.Select(faculty => faculty.Id).ToList(),
})
.ToList();
CleanUpFacultiesOnChangeTracker();
foreach (var item in cachedDataToReload)
{
var faculties = LoadFacultiesFromDb(item.FacultyIds);
typeof(Department).GetProperty("Faculties")
.SetValue(item.Department, faculties);
}
}
private void CleanUpFacultiesOnChangeTracker()
{
var changedEntries = ChangeTracker.Entries<Faculty>().Where(x => x.State != EntityState.Unchanged).ToList();
foreach (var entry in changedEntries)
{
switch (entry.State)
{
case EntityState.Modified:
entry.CurrentValues.SetValues(entry.OriginalValues);
entry.State = EntityState.Unchanged;
break;
case EntityState.Added:
entry.State = EntityState.Detached;
break;
case EntityState.Deleted:
entry.State = EntityState.Unchanged;
break;
}
}
}
private ICollection<Faculty> LoadFacultiesFromDb(IEnumerable<FacultyEnum> facultyIds)
{
var destination = new List<Faculty>();
foreach (var id in facultyIds)
{
var newFaculty = ChangeTracker
.Entries<Faculty>()
.Where(x => x.State == EntityState.Unchanged && x.Entity.Id == id)
.FirstOrDefault()
?.Entity;
if (newFaculty == null)
{
newFaculty = Set<Faculty>().Find(id) ?? id;
}
destination.Add(newFaculty);
}
return destination;
}
protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
modelBuilder.Conventions.Remove<PluralizingTableNameConvention>();
modelBuilder.Conventions.Remove<OneToManyCascadeDeleteConvention>();
modelBuilder.Conventions.Remove<ManyToManyCascadeDeleteConvention>();
modelBuilder.Properties<string>()
.Configure(p => p.HasMaxLength(100));
modelBuilder.Configurations.Add(new DepartmentConfiguration());
modelBuilder.Configurations.Add(new FacultyConfiguration());
base.OnModelCreating(modelBuilder);
}
private static string GetConnectionString()
{
return #"Data Source=(localdb)\MSSQLLocalDB;Initial Catalog=TestEnum;Integrated Security=True;Connect Timeout=30;Encrypt=False;TrustServerCertificate=True;ApplicationIntent=ReadWrite;MultiSubnetFailover=False;MultipleActiveResultSets=true;";
}
}
public class MyDbInitializer : DropCreateDatabaseIfModelChanges<MyContext>
{
protected override void Seed(MyContext context)
{
context.Faculty.SeedEnumValues<Faculty, FacultyEnum>(theEnum => theEnum);
context.SaveChanges();
base.Seed(context);
}
}
public class DepartmentConfiguration : EntityTypeConfiguration<Department>
{
public DepartmentConfiguration()
{
HasMany(x => x.Faculties)
.WithMany();
}
}
public class FacultyConfiguration : EntityTypeConfiguration<Faculty>
{
public FacultyConfiguration()
{
Property(x => x.Id)
.HasDatabaseGeneratedOption(DatabaseGeneratedOption.None);
}
}
public class Department
{
public int Id { get; private set; }
public virtual ICollection<Faculty> Faculties { get; private set; }
public Department()
{
Faculties = new List<Faculty>();
}
public void AddFaculty(FacultyEnum faculty)
{
Faculties.Add(faculty);
}
}
public class Faculty
{
public FacultyEnum Id { get; private set; }
public string Name { get; private set; }
public string Description { get; private set; }
private Faculty(FacultyEnum theEnum)
{
Id = theEnum;
Name = theEnum.ToString();
Description = theEnum.Description();
}
protected Faculty() { } //For EF
public static implicit operator Faculty(FacultyEnum theEnum) => new Faculty(theEnum);
public static implicit operator FacultyEnum(Faculty faculty) => faculty.Id;
}
public enum FacultyEnum
{
[Description("English")]
Eng,
[Description("Mathematics")]
Math,
[Description("Economy")]
Eco,
}
public static class Extensions
{
public static string Description<TEnum>(this TEnum item)
=> item.GetType()
.GetField(item.ToString())
.GetCustomAttributes(typeof(DescriptionAttribute), false)
.Cast<DescriptionAttribute>()
.FirstOrDefault()?.Description ?? string.Empty;
public static void SeedEnumValues<T, TEnum>(this IDbSet<T> dbSet, Func<TEnum, T> converter)
where T : class => Enum.GetValues(typeof(TEnum))
.Cast<object>()
.Select(value => converter((TEnum)value))
.ToList()
.ForEach(instance => dbSet.AddOrUpdate(instance));
}
The output will be:
// Department Id 1 has these faculties:
// - Math
// - Eco

map configuration or unsupported mapping

I have two types. One in the business layer:
namespace Business
{
public class Car
{
private int _id;
private string _make;
private string _model;
public int id
{
get { return _id; }
set { _id = value; }
}
public string make
{
get { return _make; }
set { _make = value; }
}
public string model
{
get { return _model; }
set { _model = value; }
}
}
}
and the other in the Data layer (Entity Framework):
namespace Data
{
using System;
using System.Collections.Generic;
public partial class Car
{
public Car()
{
this.facttables = new HashSet<facttable>();
}
public int id { get; set; }
public string make { get; set; }
public string model { get; set; }
public virtual ICollection<facttable> facttables { get; set; }
}
}
Here is the code I get from the service layer:
namespace Data
{
public class VehicleDAO : IVehicleDAO
{
private static readonly ILog log = LogManager.GetLogger(typeof(VehicleDAO));
MapperConfiguration config;
public VehicleDAO ()
{
Mapper.Initialize(cfg => cfg.CreateMap<Business.Car, Data.Car>());
config = new MapperConfiguration(cfg =>
{
cfg.CreateMap<Business.Car, Data.Car>()
.ForMember(dto => dto.facttables, opt => opt.Ignore());
//.ForMember(d => d.id, opt => opt.MapFrom(c => c.id))
//.ForMember(d => d.make, opt => opt.MapFrom(c => c.make))
//.ForMember(d => d.model, opt => opt.MapFrom(c => c.model));
});
config.AssertConfigurationIsValid();
}
public Data.Car Select(int id)
{
Data.Car car;
using (VehicleEntities VehicleDatabase = new VehicleEntities())
{
car = VehicleDatabase.Cars.Where(c => c.id == id).ToList().Single();
Business.Car cars = AutoMapper.Mapper.Map<Business.Car>(car);
}
return car;
}
The exception is: {"Missing type map configuration or unsupported mapping.\r\n\r\nMapping types:\r\nCar_70BD8401A87DAAD8F5F0EC35BCAE5C9E6EE2D6CB5A1AFCE296B313D8AD87D2E9 -> Car\r\nSystem.Data.Entity.DynamicProxies.Car_70BD8401A87DAAD8F5F0EC35BCAE5C9E6EE2D6CB5A1AFCE296B313D8AD87D2E9 -> Business.Car"}. What is wrong? I have marked the line that causes the exception (third from last line).
Automapper only maps in the direction you created the mapping in. CreateMap<Business.Car, Data.Car> creates a mapping from Business.Car to Data.Car. It looks like you are trying to map from Data.Car to Business.Car, which means you need to CreateMap<Data.Car, Business.Car>
Mapper.Initialize(cfg => cfg.CreateMap<Data.Car, Business.Car>());
config = new MapperConfiguration(cfg =>
{
cfg.CreateMap<Data.Car, Business.Car>();
});
config.AssertConfigurationIsValid();

How to properly mapping object in fluent nhibernate

Its first time when I'm using ORM.
Here is my code:
public class EwidencjonowanaRzeczMap : ClassMap<EwidencjonowanaRzecz>
{
public EwidencjonowanaRzeczMap()
{
Id(c => c.Id);
References(m => m.WagaRef);
}
}
public class WagaMap : ClassMap<Waga>
{
public WagaMap()
{
Id(m => m.Id);
Map(m => m.WagaPrzedmiotu);
HasMany(m => m.ListaRzeczy).Inverse().Cascade.All();
}
}
public class EwidencjonowanaRzecz
{
public virtual int Id { get; set; }
public virtual Waga WagaRef { get; set; }
}
public class Waga
{
public virtual int Id { get; set; }
public virtual String WagaPrzedmiotu { get; set; }
public virtual IList<EwidencjonowanaRzecz> ListaRzeczy { get; set; }
public Waga()
{
ListaRzeczy = new List<EwidencjonowanaRzecz>();
}
}
Here is my function to select records:
public IList<T> SelectAllFromTable<T>()
{
IList<T> czyDanePoprawne = null;
try
{
_sesja = NHibernateHelper.CreateSessionFactory().OpenSession();
using (_sesja.BeginTransaction())
{
czyDanePoprawne = _sesja.CreateCriteria(typeof(T)).List<T>();
}
}
catch (Exception)
{
CzyNieWystapilyBledy = true;
}
return czyDanePoprawne;
}
Tables:
ewidencjonowanarzecz [ Id - PK , IdWagi - FK (Waga.Id)]
waga [ Id - PK , WagaPrzedmiotu ]
Every type Id's - INT(3)
WagaPrzedmiotu is VARCHAR(10)
How to read to list these 2 fields?:
Id (ewidencjonowanarzecz) and WagaPrzedmiotu (waga)
In my mapping:
EwidencjaList = ModelBazy.SelectAllFromTable<EwidencjonowanaRzecz>();
is empty.
What is wrong with my mapping?
If you want to select the table record you can try this :
_sesja = NHibernateHelper.CreateSessionFactory().OpenSession();
var tabledata = _sesja.CreateQuery("from EwidencjonowanaRzecz").List<EwidencjonowanaRzecz>();
If you want to check whether if it fetches the values, try this
string value = tabledata.WagaPrzedmiotu;

Categories

Resources