Nhibernate 3.1 .Net 4.0 - Get Composite-Id from List of Query - nhibernate

I have a MS SQL db with a table that has a composite id.
This is my xml configuration file:
<?xml version="1.0" encoding="utf-8" ?>
<hibernate-mapping xmlns="urn:nhibernate-mapping-2.2"
assembly="SimpleMapping.Domain"
namespace="SimpleMapping.Domain">
<class name="TabMaster" table="TabMaster">
<composite-id class="TabMasterCompositeKey">
<key-property column="Configuration" name="Configuration" type="AnsiString" />
<key-property column="ResolutionType" name="ResolutionType" type="int" />
</composite-id>
<property name="Description" column="Description" type="AnsiString" />
<property name="Title" column="Title" type="AnsiString" />
<property name="IdResolutionFileDes" column="idResolutionFileDes" type="AnsiString" />
<property name="WorkflowType" column="WorkflowType" type="AnsiString" />
<property name="ViewAllStep" column="ViewAllStep" type="AnsiString" />
<property name="ManagedData" column="ManagedData" type="AnsiString" />
</class>
</hibernate-mapping>
I have created my mapping objects:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace SimpleMapping.Domain
{
public class TabMaster
{
public virtual string Configuration { get; set; }
public virtual int ResolutionType { get; set; }
public virtual string Description { get; set; }
public virtual string Title { get; set; }
public virtual string IdResolutionFileDes { get; set; }
public virtual string WorkflowType { get; set; }
public virtual string ViewAllStep { get; set; }
public virtual string ManagedData { get; set; }
}
}
and
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace SimpleMapping.Domain
{
class TabMasterCompositeKey
{
public virtual string Configuration { get; set; }
public virtual int ResolutionType { get; set; }
public override bool Equals(object obj)
{
TabMasterCompositeKey compareTo = (TabMasterCompositeKey)obj;
return (this.Configuration == compareTo.Configuration) && (this.ResolutionType == compareTo.ResolutionType);
}
public override int GetHashCode()
{
return this.ToString().GetHashCode();
}
public override string ToString()
{
return Configuration.ToString() + "/" + ResolutionType.ToString();
}
}
}
In my Main() I try to list the elements in the table doing:
namespace SimpleMapping.Console
{
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using NHibernate;
using NHibernate.Cfg;
using SimpleMapping.Domain;
class Program
{
static void Main(string[] args)
{
ISessionFactory sessionFactory = new Configuration().Configure().BuildSessionFactory();
using (ISession session = sessionFactory.OpenSession())
{
using (ITransaction tx = session.BeginTransaction())
{
IQuery query = session.CreateQuery("from TabMaster");
foreach (TabMaster tm in query.List<TabMaster>())
System.Console.WriteLine(string.Format("ID: {0}\nConfiguration: {1}\nManagedData: {2}\n", tm.Configuration, tm.Description, tm.ManagedData));
tx.Commit();
session.Close();
}
}
System.Console.ReadKey();
}
}
}
and I can see the parameters that are not a key.
So I can see Description and ManagedData but I can't see tm.Configuration : in the stack is set to Null for every record.
What's the problem?
I think this is related to the composite-id rule (?)
Thank you for your reply!

You should name the composite key:
<composite-id class="TabMasterCompositeKey" name="TheKey">
<key-property column="Configuration" name="Configuration" type="AnsiString" />
<key-property column="ResolutionType" name="ResolutionType" type="int" />
</composite-id>
and put a property in the TabMaster entity:
public class TabMaster
{
public virtual TabMasterCompositeKey TheKey { get; set; }
public virtual string Description { get; set; }
public virtual string Title { get; set; }
public virtual string IdResolutionFileDes { get; set; }
public virtual string WorkflowType { get; set; }
public virtual string ViewAllStep { get; set; }
public virtual string ManagedData { get; set; }
}
with this you will be able to see the single key property on the entity.

Related

ASP.NET Core Web API Not Returning List of Child Items

I am creating a ASP.NET Core web API that uses EF Core. I have a GET endpoint that returns a list of reports from the database. I have a related table which stores screenshots for the reports. The reportId is the foreign key in the images table.
I have a List item in the reports class which points to the ImagesList class.
I have the foreign key reportId in the ImageList class and identified as a foreign key. I also have a navigation property setup to the Reports class.
Reports Class:
[Table("Vw_ReportsList", Schema = "pbi")]
public class Reports
{
[Key]
public string reportId { get; set; }
[Required]
public string reportName { get; set; }
public string reportDescription { get; set; }
public string reportType { get; set; }
public string reportAuthor { get; set; }
public string reportLastUpdate { get; set; }
public string reportLastExecution { get; set; }
public List<ImagesList> Screenshots { get; set; }
//collection navigation property
}
ImageList Class:
[Table("Vw_ScreenshotsList", Schema = "pbi")]
public class ImagesList
{
[Key]
public int id { get; set; }
public string fileNameTest { get; set; }
public string imageData { get; set; }
public string created { get; set; }
public string reportId { get; set; }
[ForeignKey("reportId")]
public virtual Reports Reports { get; set; }
//navigation property
}
Context:
public class ServiceCatalogContext : DbContext
{
public ServiceCatalogContext(DbContextOptions<ServiceCatalogContext> options) : base(options) { }
public DbSet<Reports> Reports { get; set; }
public DbSet<ImagesList> ImagesLists { get; set; }
public DbSet<Images> Images { get; set; }
//used for the image upload POST call
protected override void OnModelCreating(ModelBuilder modelBuilder)
{
// modelBuilder.Entity<ImagesList>().HasOne<Reports>().WithMany().HasForeignKey(s => s.reportId);
modelBuilder.Entity<ImagesList>().HasOne(s => s.Reports).WithMany(s => s.Screenshots).HasForeignKey(s => s.reportId);
modelBuilder.Entity<Reports>().HasMany(r => r.Screenshots).WithOne().HasForeignKey(r => r.reportId);
}
}
My API works and returns the list of reports with no errors but I do not receive the screenshots list that I am expecting.
Here is a sample of the API output:
{
"reportId": "AC79F4CD-3771-42B2-B7F8-46AE4CE8DC80",
"reportName": "Dashboard Usage Metrics Report",
"reportDescription": "DESCRIPTION HERE - Dashboard Usage Metrics Report",
"reportType": "Excel",
"reportLastUpdate": "07/22/2020",
"reportLastExecution": "07/23/2020"
},
{
"reportId": "138CD5FA-6B5A-4C63-A449-DA9A9BBBF689",
"reportName": "Report Usage Metrics Report",
"reportDescription": "DESCRIPTION HERE - Report Usage Metrics Report",
"reportType": "Excel",
"reportLastUpdate": "07/22/2020",
"reportLastExecution": "07/23/2020"
}
I not receiving any error message from the API so I am not sure what I missed in order for each report to return the related images.
Edit: Adding Controller action
[HttpGet]
[EnableQuery()] //enabled OData querying
public IQueryable<Reports> Get()
{
return _context.Reports;
}
Edit: Updated ImagesList class
I also have Odata installed so here the metadata if that is of help:
<?xml version="1.0" encoding="utf-8"?>
<edmx:Edmx Version="4.0" xmlns:edmx="http://docs.oasis-open.org/odata/ns/edmx">
<edmx:DataServices>
<Schema Namespace="ServiceCatalog.API.Entities" xmlns="http://docs.oasis-open.org/odata/ns/edm">
<EntityType Name="Reports">
<Key>
<PropertyRef Name="reportId" />
</Key>
<Property Name="reportId" Type="Edm.String" Nullable="false" />
<Property Name="reportName" Type="Edm.String" Nullable="false" />
<Property Name="reportDescription" Type="Edm.String" />
<Property Name="reportType" Type="Edm.String" />
<Property Name="reportLastUpdate" Type="Edm.String" />
<Property Name="reportLastExecution" Type="Edm.String" />
<NavigationProperty Name="Screenshots" Type="Collection(ServiceCatalog.API.Entities.ImagesList)" />
</EntityType>
<EntityType Name="ImagesList">
<Key>
<PropertyRef Name="id" />
</Key>
<Property Name="id" Type="Edm.Int32" Nullable="false" />
<Property Name="fileNameTest" Type="Edm.String" />
<Property Name="imageData" Type="Edm.String" />
<Property Name="created" Type="Edm.String" />
<Property Name="reportId" Type="Edm.String" />
<NavigationProperty Name="Reports" Type="ServiceCatalog.API.Entities.Reports">
<ReferentialConstraint Property="reportId" ReferencedProperty="reportId" />
</NavigationProperty>
</EntityType>
</Schema>
<Schema Namespace="Default" xmlns="http://docs.oasis-open.org/odata/ns/edm">
<EntityContainer Name="Container">
<EntitySet Name="reports" EntityType="ServiceCatalog.API.Entities.Reports" />
</EntityContainer>
</Schema>
</edmx:DataServices>
</edmx:Edmx>
Design your model like below:
[Table("Vw_ReportsList", Schema = "pbi")]
public class Reports
{
[Key]
public string reportId { get; set; }
[Required]
public string reportName { get; set; }
public string reportDescription { get; set; }
public string reportType { get; set; }
public string reportAuthor { get; set; }
public string reportLastUpdate { get; set; }
public string reportLastExecution { get; set; }
public List<ImagesList> Screenshots { get; set; }
//collection navigation property
}
[Table("Vw_ScreenshotsList", Schema = "pbi")]
public class ImagesList
{
[Key]
public int id { get; set; }
public string fileNameTest { get; set; }
public string imageData { get; set; }
public string created { get; set; }
public string reportId { get; set; }
// [ForeignKey("reportId")]
public virtual Reports Reports { get; set; }
//navigation property
}
And your DbContext:
protected override void OnModelCreating(ModelBuilder modelBuilder)
{
modelBuilder.Entity<ImagesList>().HasOne(s => s.Reports)
.WithMany(s => s.Screenshots).HasForeignKey(s => s.reportId);
//modelBuilder.Entity<Reports>().HasMany(r => r.Screenshots).WithOne().HasForeignKey(r => r.reportId);
}
Your controller:
[HttpGet]
public IQueryable<Reports> Get()
{
return _context.Reports.Include(r=>r.Screenshots);
}
Be sure to install Microsoft.AspNetCore.Mvc.NewtonsoftJson then use the following code:
services.AddControllers().AddNewtonsoftJson(options =>
{
options.SerializerSettings.ReferenceLoopHandling = ReferenceLoopHandling.Ignore;
});

NHibernate - Could not compile the mapping document

It is my firs time using NHibernate, I'm getting source code for a program from my friend after that, the program is running well after that I'm trying to add "Stock.hbm.xml" as following:
`
<?xml version="1.0" encoding="utf-8"?>
<hibernate-mapping xmlns="urn:nhibernate-mapping-2.2"
namespace="NBooks.Core.Models"
assembly="NBooks.Core">
<class name="Stock" table="Stocks" lazy="false">
<id name="ID">
<column name="Stock_ID" />
<generator class="identity" />
</id>
<property name="Stock_name" column="Stock_name" />
<property name="Comp_ID" column="Comp_ID" />
<property name="Stock_Code" column="Stock_Code" />
<property name="Address" column="Address" />
<property name="Nots" column="Nots" />
</class>
</hibernate-mapping>
`
with my class "Stock.cs"
using System;
using System.Collections.Generic;
namespace NBooks.Core.Models
{
public class Stock : BaseModel<Stock>
{
public virtual string Stock_name { get; set; }
public virtual string Stock_Code { get; set; }
public virtual int Comp_ID { get; set; }
public virtual string Notes { get; set; }
public virtual string Address { get; set; }
public virtual bool Inactive { get; set; }
public Stock()
{
}
public Stock(string name)
{
this.Stock_name = name;
}
}
public class StockEventArgs : EventArgs
{
public Stock Stock { get; set; }
public StockEventArgs(Stock Stock)
{
this.Stock = Stock;
}
}
public delegate void StockEventHandler(Stock sender, EventArgs e);
}
the Base model is:
using System;
using System.Collections.Generic;
using NBooks.Core.Util;
using NBooks.Data.NHibernate;
using NHibernate;
namespace NBooks.Core.Models
{
public interface IBaseModel
{
int Id { get; set; }
}
public class BaseModel<T> : IBaseModel
{
IList<string> errors = new List<string>();
public virtual int Id { get; set; }
public virtual bool HasErrors {
get { return errors.Count > 0; }
}
public virtual IList<string> Errors {
get { return errors; }
}
public BaseModel()
{
}
public virtual void Validate()
{
Errors.Clear();
}
public virtual void SaveOrUpdate()
{
ITransaction trans = null;
try {
ISession session = NHibernateHelper.OpenSession();
trans = session.BeginTransaction();
session.SaveOrUpdate(this);
session.Flush();
trans.Commit();
} catch (Exception ex) {
LoggingService.Error(ex.Message);
MessageService.ShowError(ex.Message);
trans.Rollback();
}
}
public virtual void Delete()
{
ITransaction trans = null;
try {
ISession session = NHibernateHelper.OpenSession();
trans = session.BeginTransaction();
session.Delete(this);
session.Flush();
trans.Commit();
} catch (Exception ex) {
LoggingService.Error(ex.Message);
MessageService.ShowError(ex.Message);
trans.Rollback();
}
}
public static T Read(int id)
{
return NHibernateHelper.OpenSession().Load<T>(id);
}
public static IList<T> FindAll()
{
return
NHibernateHelper.OpenSession().CreateCriteria(typeof(T)).List<T>();
}
}
}
when build it appers every thing is well and no errors , when run the error "NHibernate - Could not compile the mapping document Stock.hbm.xml" appears.
Thanx in advance
I noticed you have a typo in you XML:
<property name="Nots" column="Nots" />
I would suggest that you look into using Fluent NHibernate as well. It is strongly typed (for the most part) and the mapping files are easier to read and use lambda expressions so that you don't have to go the XML route.
Your mapping would instead look like this:
public class StockMap(): ClassMap<Stock>
{
public StockMap(){
Id(x => x.Id).Column("Stock_ID").GeneratedBy.Identity();
Map(x => x.Comp_ID);
Map(x => x.Address);
Map(x => x.Notes);
}
}
You have a typo in your mapping
<property name="Nots" column="Nots" />
should be
<property name="Notes" column="Nots" />

Insert in two related table at once with Nhibernate

I have two entities like
public class Person
{
public int PersonId { get; set; }
public string Name { get; set; }
public int DataId { get; set; }
}
public class Data
{
public int DataId { get; set; }
public string details { get; set; }
public int PersnId{ get; set; }
}
as you see both table are relate to each other. I want a solution to insert data in both table at once. I 1-insert person, 2-insert data and then update person and it works but I'm looking for way to eliminate Update.
My mapping for person table:
<?xml version="1.0" encoding="utf-8" ?>
<hibernate-mapping xmlns="urn:nhibernate-mapping-2.2" namespace="TestNhibrinate" assembly="TestNhibrinate">
<class name="TestNhibrinate.Entites.Person" table="Person" lazy="false">
<id name="PersonId" column="PersonId" type="int" >
<generator class="identity" />
</id>
<property name="Name" column="Name" type="String" length="50" />
<many-to-one name="Adress" class="TestNhibrinate.Entites.Adress" column="AdressId"/>
</class>
</hibernate-mapping>
and same mapping for data.
You entities should look like this:
public class Person
{
public Person()
{
DataCollection = new List<Data>();
}
public int PersonId { get; set; }
public string Name { get; set; }
public int DataId { get; set; }
public IList<Data> DataCollection{get;set;}
public void AddData(Data item)
{
if(!DataCollection.Contains(item))
{
DataCollection.Add(item);
}
}
}
public class Data
{
public int DataId { get; set; }
public string details { get; set; }
public Person Person{ get; set; }
}
This way you create a one-to-many relation from Person to Data. If you save your person entity after you added some data, the data will also be persisted. This depends on your cascade options offcourse.
I'm not sure how to map this with XML mappings, since i always use Fluent or Auto mappings.

Nhibernate mapping

I am trying to map Users to each other. The senario is that users can have buddies, so it links to itself
I was thinking of this
public class User
{
public virtual Guid Id { get; set; }
public virtual string FirstName { get; set; }
public virtual string LastName { get; set; }
public virtual string EmailAddress { get; set; }
public virtual string Password { get; set; }
public virtual DateTime? DateCreated { get; set; }
**public virtual IList<User> Friends { get; set; }**
public virtual bool Deleted { get; set; }
}
But am strugling to do the xml mapping.
<?xml version="1.0" encoding="utf-8" ?>
<hibernate-mapping xmlns="urn:nhibernate-mapping-2.2"
assembly="MyVerse.Domain"
namespace="MyVerse.Domain" >
<class name="User" table="[User]">
<id name="Id">
<generator class="guid" />
</id>
<property name="FirstName" />
<property name="LastName" />
<property name="EmailAddress" />
<property name="Password" />
<property name="DateCreated" />
<property name="Deleted" />
<set name="Friends" table="UserFriend">
<key foreign-key="Id"></key>
<many-to-many class="User"></many-to-many>
</set>
</class>
</hibernate-mapping>
something like
<bag name="Friends" table="assoc_user_table" inverse="true" lazy="true" cascade="all">
<key column="friend_id" />
<many-to-many class="User,user_table" column="user_id" />
</bag>
Consider using the repository pattern. Create a Repository contract and a base abstract class that takes one of your entities as a type (your mapped class)
Open the session when the repository is initialized and close when destroyed. (implement IDisposable).
Then make sure all of your access to the session happens within the using statement:
[pseudo-code]:
using(var repository = RepositoryFactory<EntityType>.CreateRepository())
{
var entity = repository.get(EntityID);
foreach (somesubclass in entity.subclasscollection)
{
//Lazy loading can happen here, session is still open with the repository
... Do Something
}
}
I use a base abstract class for my Repositories. This one is for my readonly repository but you'll get the drift. They key is to keep your units of work small, open the session only when you have something to do with the database, then let it close on the dispose. Here's the base class, disclaimer YMMV:
public interface IEntity
{
int Id { get; set; }
}
public interface IRORepository<TEntity> : IDisposable where TEntity : IEntity
{
List<TEntity> GetAll();
TEntity Get(int id);
}
public abstract class RORepositoryBase<T> : IRORepository<T> where T : IEntity
{
protected ISession NHibernateSession;
protected RORepositoryBase()
{
NHibernateSession = HibernateFactory.OpenSession();
NHibernateSession.DefaultReadOnly = true;
}
public ISession Session { get { return NHibernateSession; } }
public void Dispose()
{
NHibernateSession.Flush();
NHibernateSession.Close();
NHibernateSession.Dispose();
}
public virtual List<T> GetAll()
{
return NHibernateSession.Query<T>().ToList();
}
public virtual T Get(int id)
{
return NHibernateSession.Get<T>(id);
}
}

Querying Overriding Entities Using a Self Join and the NHibernate Criteria API

I have a simple Waiver model, and I would like to make a query that returns all the Waivers that are not overridden.
public class Waiver
{
private readonly int id;
protected Waiver()
{
this.id = 0;
}
public virtual int Id { get { return id; } }
public virtual string Name { get; set; }
public virtual string Description { get; set; }
public virtual bool IsRequired { get; set; }
public virtual DateTime EffectiveDate { get; set; }
public virtual Waiver OverriddenWaiver { get; set; }
}
Here's the map:
<class name="Waiver" table="Music_Waivers">
<id name="id" access="field" column="WaiverId" unsaved-value="0">
<generator class="native" />
</id>
<property name="Name" column="Name" />
<property name="Description" column="Description" />
<property name="IsRequired" column="IsRequired" />
<property name="EffectiveDate" column="EffectiveDate" />
<many-to-one name="OverriddenWaiver" class="Waiver" column="OverrideWaiverId" />
</class>
Now I want to have a method in my Repository with the signature public IList GetLatest(). For some reason I'm having a hard time implementing this with the CriteriaAPI. I can write this in T-SQL no problem.
I ended up brute forcing a solution. It's not pretty, but since I know the table will be tiny (probably going to end up being only 5 rows) I came up with the following code solution:
public IList<Waiver> GetLatest()
{
using (var session = SessionManager.OpenSession())
{
var criteria = session.CreateCriteria(typeof (Waiver));
var waivers = criteria.List<Waiver>();
var nonOverridenWaivers = new List<Waiver>();
foreach(var waiver in waivers)
{
bool overrideExists = waivers.Any(w => w.Overrides != null &&
w.Overrides.Id == waiver.Id);
if (!overrideExists)
nonOverridenWaivers.Add(waiver);
}
return nonOverridenWaivers;
}
}