I have an issue when deleting a child record from the session. Here are the entities i have defined:
public class ReportedData
{
public virtual int ReportedDataID { get; set; }
public virtual ReportedDataTypes Type { get; set; }
public virtual string Reason { get; set; }
public virtual IList<ArticleCommentReported> ArticleCommentsReported { get; private set; }
public virtual IList<ForumPostReported> ForumPostsReported { get; private set; }
public ReportedData()
{
ArticleCommentsReported = new List<ArticleCommentReported>();
ForumPostsReported = new List<ForumPostReported>();
}
}
public class ArticleCommentReported : ReportedData
{
public virtual ArticleComment Comment { get; set; }
}
public class ForumPostReported : ReportedData
{
public virtual ForumPost Post { get; set; }
}
With the following fluent mapping:
public ReportedDataMap()
{
Table("ReportedData");
Id(x => x.ReportedDataID);
Map(x => x.Type, "TypeID");
Map(x => x.Reason);
HasMany(x => x.ArticleCommentsReported)
.KeyColumn("ReportedDataID")
.Inverse()
.Cascade.All();
HasMany(x => x.ForumPostsReported)
.KeyColumn("ReportedDataID")
.Inverse()
.Cascade.All();
}
public class ArticleCommentReportedMap : SubclassMap<ArticleCommentReported>
{
public ArticleCommentReportedMap()
{
Table("ArticleCommentsReported");
KeyColumn("ReportedDataID");
References(x => x.Comment, "CommentID");
}
}
public class ForumPostReportedMap : SubclassMap<ForumPostReported>
{
public ForumPostReportedMap()
{
Table("ForumPostsReported");
KeyColumn("ReportedDataID");
References(x => x.Post, "PostID");
}
}
Now say i try the following (i have added comments to help you understand what's going on):
// Loop over the reported data (this is my view model and not my actual model which contains an extra property for the action they wish to carry out)
foreach (var reportedData in model)
{
// If the action is leave then do nothing (else we always delete the reported data)
if (reportedData.Action != ReportedDataActions.Leave)
{
// Switch over the type since we need to make sure it deletes the article comment or post if the action is set to delete
switch (reportedData.Type)
{
case ReportedDataTypes.ArticleComment:
var reportedComment = _context.Repository<ArticleCommentReported>().GetByID(reportedData.ReportedDataID);
if (reportedData.Action == ReportedDataActions.Delete)
_context.Repository<ArticleComment>().Delete(reportedComment.Comment);
_context.Repository<ArticleCommentReported>().Delete(reportedComment);
break;
case ReportedDataTypes.ForumPost:
var reportedPost = _context.Repository<ForumPostReported>().GetByID(reportedData.ReportedDataID);
if (reportedData.Action == ReportedDataActions.Delete)
_forumService.DeletePost(reportedPost.Post);
_context.Repository<ForumPostReported>().Delete(reportedPost);
break;
}
}
}
_context.Commit();
When the user trys to delete a forum post (the Action against the reported data is set to delete) it throws the following error:
Row was updated or deleted by another transaction (or unsaved-value mapping was incorrect): [ForumPostReported#2]
I could probably set some mapping up to automatically delete the post/comment once the reported data is deleted but i only want to delete the post/comment if the action is set to delete.
I'd appreciate it if someone could help. Thanks
Problem solved! I just had to delete the reported item first. Seems kinda backwards but it works and that's all i care.
Related
so I have an entity named Event which contains many Reports (one to many) which contains many sources (many to many).
I'm facing a problem that I just cant figure out, when I'm trying to update my event, it will try to update the report because of the cascade (which is fine)
and it will try to update the report's sources on the join table because of the cascade (which is fine), but for some reason it also tries to update the Source entity, which it shouldn't update because there is no change in it.
public class Event
{
public virtual IList<Report> Reports { get; set; }
public virutal int Id { get; set; }
public Event()
{
Reports = new List<Report>();
}
}
public class EventMapping : ClassMap<Event>
{
public EventMapping()
{
Table("EVENTS");
Id(x => x.Id).Column("ID").GeneratedBy.Sequence("EVENT_ID_SEQ");
HasMany(x => x.Reports).KeyCoulmn("EVENT_ID").Cascade.SaveUpdate();
}
}
public class Report
{
public virtual int Id { get; set; }
public virtual int Status { get; set; }
public virtual IList<Source> Sources { get; set; }
public Report()
{
Sources = new List<Source>();
}
}
public class ReportMapping : ClassMap<Report>
{
public ReportMapping()
{
Table("REPORTS");
Id(x => x.Id).Column("ID").GeneratedBy.Sequence("DIVUACH_ID_SEQ");
Map(x => x.Status).Column("Status");
HasManyToMany(x => x.Sources).Table("SOURCES_IN_REPORT").ParentKeyColumn("REPORT_ID").ChildKeyColumn("KOD_SOURCE").Cascade.All();
}
}
public class Source
{
public virtual int Id { get; set; }
}
public class SourceMapping : ClassMap<Source>
{
public SourceMapping()
{
Table("SOURCE");
Id(x => x.Id).Column("ID");
}
}
here is what I do and when it fails.
var eventFromDb = _session.Get<Event>(eventId);
eventFromDb.Reports.ToList().ForEach(x => x.Status = GetStatus());
_session.Update(eventFromDb);
Any idea why?
Unwanted updates usually are cause be accidental changes of properties. NHibernate has automatic change tracking and updates all records when the properties do not return the exact same value that is assigned to it when loading.
See this answers:
Why hibernate always call "update" statement after using "select" statement in MySQL?
Nhibernate doing updates on select?
by the way, you do not need to call update(). NHibernate updates changed entities anyway when they are in the session. Everything you load from the database (e.g. by session.get() in your case) is in the session. Just commit the transaction.
I have a simple many-to-many relationship using Fluent NHibernate and it is working pretty fine.
Here is my first class mapping:
public LobMapping()
{
...
HasManyToMany(x => x.Commodities)
.Table("PPBSYS.LOB_COMMODITY")
.ParentKeyColumn("LOB_ID")
.ChildKeyColumn("COMMODITY_ID")
.Cascade.SaveUpdate()
.LazyLoad();
...
}
Here is my second class mapping:
public CommodityMapping()
{
...
HasManyToMany(x => x.Lobs)
.Table("PPBSYS.LOB_COMMODITY")
.ParentKeyColumn("COMMODITY_ID")
.ChildKeyColumn("LOB_ID")
.Inverse()
.Cascade.All()
.LazyLoad();
...
}
And finally, my Lob object has a list of commodities:
public class Lob
{
...
public virtual IEnumerable<Commodity> Commodities { get; set; }
...
}
However I am not happy with the fact that I must reference the entire commodity inside the Lob class. I really would like to do:
var lob = new Lob();
lob.Commodities = new [] { new Commodity { CommodityId = 1 }};
repository.SaveLob(lob);
But if I run the code above, NHibernate will try to update the Commodity table setting the columns to null for the commodity with ID = 1.
So actually I must get the entire object, before saving the Lob:
var lob = new Lob();
lob.Commodities = new [] { repostitory.GetCommodit(1) };
repository.SaveLob(lob);
And I know that the commodity exists, because the user just have selected them.
It is possible to accomplish my task?
I assume your repository is calling session.Get<T>(id) under the covers. There is also session.Load<T>(id).
lob.Commodities = new [] { session.Load<Commodity>(1) };
From the NHibernate documentation on Load()...
If the class is mapped with a proxy, Load() returns an object that is an uninitialized proxy and does not actually hit the database until you invoke a method of the object. This behaviour is very useful if you wish to create an association to an object without actually loading it from the database.
Daniel's answer sounds promising, let me know if in Save the proxy won't hit the database to fill all the properties of the entity.
Another answer would be a little forcefully on Nhibernate, i tested it and it's working,
working code :
public class Com
{
public virtual Guid ID { get; set; }
public virtual string Name { get; set; }
public virtual IList<Lob> Lobs { get; set; }
}
public class Lob
{
public virtual Guid ID { get; set; }
public virtual string Name { get; set; }
public virtual IList<Com> Coms { get; set; }
}
class LobMap : ClassMap<Lob>
{
public LobMap()
{
Id(x => x.ID).GeneratedBy.GuidComb();
Map(x => x.Name);
HasManyToMany(x => x.Coms)
.Table("LOB_COM")
.ParentKeyColumn("LOB_ID")
.ChildKeyColumn("COM_ID")
.Cascade.SaveUpdate()
.LazyLoad();
}
}
class ComMap : ClassMap<Com>
{
public ComMap()
{
Id(x => x.ID).GeneratedBy.GuidComb();
Map(x => x.Name);
HasManyToMany(x => x.Lobs)
.Table("LOB_COM")
.ParentKeyColumn("COM_ID")
.ChildKeyColumn("LOB_ID")
.Inverse()
.Cascade.All()
.LazyLoad();
}
}
Now - I set a dummy entity to mimic the connection table and map it :
public class ComLobConnection
{
public virtual Guid ComID { get; set; }
public virtual Guid LobID { get; set; }
}
public class ComLobConnectionMap : ClassMap<ComLobConnection>
{
public ComLobConnectionMap()
{
Table("LOB_COM");
Id();
Map(x => x.ComID,"COM_ID");
Map(x => x.LobID,"LOB_ID");
}
}
Notice that i'm mapping to exact same fields and Table as the ManyToMany, with no ID set up (that's the empty Id() call)
Now all that's left is to save a ComLobConnection and it will be added to the Com.Lobs and Lob.Coms
Saved some test Com,Lob
var testCom = new Com() { Name = "TestCom" };
var testLob = new Lob() { Name = "TestLob" };
session.SaveOrUpdate(testCom);
session.SaveOrUpdate(testLob);
after save - took their ID's and saved a connection to test
var testConnection = new ComLobConnection()
{
ComID = Guid.Parse("D3559F53-8871-45E9-901D-A22800806567"),
LobID = Guid.Parse("D372D430-2E61-44F2-BA89-A228008065F1")
};
session.SaveOrUpdate(testConnection);
This forced a new record in the manytomany table, and worked when getting both Lob and Com after.
I'm not recommending this :), It just interested me if it can be done, and it can.
This way you will not hit the DB for loading Coms or Lobs that you know exist to save their connection.
Hopefully Load() will not hit the DB for that too :)
Edit : can be done with any kind of ID
public class Category
{
public virtual int Id { set; get; }
public virtual string Name { set; get; }
public virtual int CategoryOrder { set; get; }
public virtual IEnumerable<News> LatestNews { set; get; }
}
public sealed class CategoryMap :ClassMap<Category>
{
public CategoryMap()
{
LazyLoad();
Id(x => x.Id);
Map(x => x.Name);
Map(x => x.CategoryOrder);
HasMany(x => x.LatestNews);
}
}
IRepository<Category> newsRepo = new NHibernateRepository<Category>();
using(var session = newsRepo.GetSessionFactory().OpenSession())
using(var transaction = session.BeginTransaction())
{
var result = session.Query<Category>().OrderBy(x => x.CategoryOrder);
transaction.Commit();
}
I have this category class Which I want to display a (only one) News per category. Is this correct mapping? or should i change it to Map
When i run this, it gets all the news per category. But i want the latest news per category (only one). I can get the latest news by querying News.DateUpdated.
How should i change the query to get one news per category?
or how do I get some of the News? ie: limit the number of news I can query?
I think you can have your cake and eat it too. You have a list of News items, so just leave that. But add in another property that gets just the News item you want.
public class Category
{
public virtual int Id { set; get; }
public virtual string Name { set; get; }
public virtual int CategoryOrder { set; get; }
public virtual IEnumerable<News> AllNews { set; get; }
public virtual News LatestNews
{
get
{
// probably needs some work
return this.AllNews.OrderByDescending(n => n.SomeDateField).Take(1);
}
}
}
public sealed class CategoryMap :ClassMap<Category>
{
public CategoryMap()
{
LazyLoad();
Id(x => x.Id);
Map(x => x.Name);
Map(x => x.CategoryOrder);
HasMany(x => x.AllNews);
}
}
you can use lazy mode extra to achieve this,
public News GetLatestNews(Category cat)
{
var session = SessionFactory.CurrentSession;
var news = session.CreateFilter(cat.LatestNews , "order by categoryorder").SetFirstResult((page - 1) * pageSize).SetFirstResult(0).SetMaxResults(1).List().FirstOrDefault();
return news;
}
however if you try to access the LatestNews collection directly, this won't be of any use as it will load all the news objects associated with Category from db which would lower the performance.
Is there a way I can setup mapping for a table that doesn't have a direct reference to another table? It actually gets it's reference from another table that I do have a direct reference from.
This is what I have so far, but I'm not sure how to map the "LookupValue" in my MetaData model. It would need to map to MetaData if the [mdd].DefinitionType equals the [mdl].LookupType and the [md].DataValue equals the [mdl].LookupKey.
public class MetaData {
public virtual long TableID { get; set; }
public virtual MetaDataDefinition Definition { get; set; }
public virtual int DefinitionID { get; set; }
public virtual String DataValue { get; set; }
public virtual MetaDataLookup LookupValue { get; set; }
public override bool Equals(object obj) { ... }
public over int GetHashCode() { ... }
}
public class MetaDataDefinition {
public virtual long ID { get; set; }
public virtual string DefinitionName { get; set; }
public virtual string DefinitionType { get; set; }
}
public class MetaDataLookup {
public virtual string Type { get; set; }
public virtual string LookupKey { get; set; }
public virtual string LookupValue { get; set; }
public override bool Equals(object obj) { ... }
public over int GetHashCode() { ... }
}
public class MetaDataMap : ClassMap<MetaData> {
public MetaDataMap() {
Table("PPOMetaData");
CompositeId()
.KeyProperty(x => x.TableID, "TableID")
.KeyProperty(x => x.DefinitionID, "DefinitionID");
References(x => x.Defintion, "DefinitionID").Not.LazyLoad().Cascade.All().Fetch.Join();
Map(x => x.TableID);
Map(x => x.DataValue);
}
}
public class MetaDataDefinitionMap : ClassMap<MetaDataDefinition> {
public MetaDataDefinitionMap() {
Table("MetaDataDefinitions");
Id(x => x.ID);
Map(x => x.DefinitionName);
Map(x => x.Type);
}
}
public class MetaDataLookupMap : ClassMap<MetaDataLookup> {
public MetaDataLookupMap() {
CompositeId()
.KeyProperty(x => x.LookupType)
.KeyProperty(x => x.LookupKey);
Map(x => x.LookupValue);
}
}
Ideally, I want to have it run a query similar to this:
SELECT data.TableID, data.DefinitionID, def.DefinitionName, data.DataValue,lu.LookupValue AS DataValue
FROM dbo.PPOMetadata AS data
INNER JOIN dbo.MetaDataDefinitions AS def ON def.ID = data.DefinitionID
LEFT OUTER JOIN dbo.MetaDataLookup AS lu ON lu.LookupType = def.Type AND lu.LookupKey = data.DataValue
WHERE data.TableID = 1
In terms of update ability, the only thing I would ever create, update or delete would be in the MetaData table. The definitions and Lookup values would never change (at least from this part of the application). Is mapping the "MetaDataLookup" directly to the MetaData model possible? If so, can someone point me in the right direction of what I should be looking at?
Thanks!
I came up with a workaround that seems to be working and might take some of the complexity out. Instead of trying to handle the complex joins in a ClassMap, I built a view in Sql Server that does this for me. In my application, I built a new Model and ClassMap for the view. I haven't implemented any update logic yet, but I think I'll have the update logic work directly on the MetaData model, while the read logic (which needs everything joined together) will use the new MetaDataView model.
I'm still curious if complex joins like this are possible in Fluent NHibernate, but for now this solution seems to be working for me.
i'm new to nhibernate so maybe the response depends on my lack of knowledge.
I created these two tables:
(sorry for italian language, i hope you can understand withouth any problems).
Then, i have these object in my model:
[Serializable]
public class Profilo
{
public virtual int Id { get; set; }
public virtual string Matricola { get; set; }
public virtual string Ruolo { get; set; }
public virtual IList ListaSedi { get; set; }
public Profilo()
{
ListaSedi = new List();
}
}
[Serializable]
public class Sede
{
public virtual string CodiceSede { get; set; }
public virtual string DescrizioneSede { get; set; }
public virtual Profilo Profilo { get; set; }
}
This is the way i mapped entities using fluent nhibernate:
public class Map_Sede : FluentNHibernate.Mapping.ClassMap
{
public Map_Sede()
{
Table("TBA_Sede");
Id(x => x.CodiceSede).Column("codice_sede").GeneratedBy.Assigned();
Map(x => x.DescrizioneSede)
.Column("descrizione");
References(prof => prof.Profilo)
.Column("codice_sede");
}
}
public class Map_Profilo : FluentNHibernate.Mapping.ClassMap
{
public Map_Profilo()
{
Table("TBA_Profilo");
Id(x => x.Id).Column("id").GeneratedBy.Identity();
Map(x => x.Matricola)
.Column("matricola");
Map(x => x.Ruolo)
.Column("ruolo");
HasMany(x => x.ListaSedi)
.AsBag()
.KeyColumns.Add("codice_sede")
.Not.LazyLoad()
.Cascade.None();
}
}
Now, i'd like to insert a new Profilo instance on my. Everything seems to work but nhibernate does not insert values on TBA_Profilo.codice_sede column. I noticed that the insert statement is composed by two parameters (matricola, ruolo) - why does it forget the third parameter?
I read somewhere (on nhibernate mailing list) that's quite normal 'cause nhiberate insert values with null first and then update the same records with right values contained in the list property.
Is it right?
Am i doing any errors?
I hope to have clarified the situation.
thx guys
ps: I'm using Nhibernate 2.1 and fluent nhibernate 1.1
UPDATE: This is the code i use to save entity.
var sesionFactory = NHibernateHelper.createSessionFactory();
using (NHibernate.ISession session = sesionFactory.OpenSession())
{
using (var transaction = session.BeginTransaction())
{
try
{
session.SaveOrUpdate(entity);
transaction.Commit();
session.Flush();
}
catch (Exception)
{
transaction.Rollback();
throw;
}
finally
{
transaction.Dispose();
}
}
}
UPDATE 2: Following sly answer i slightly modified my solution. These are new model entities:
[Serializable]
public class Profilo
{
public virtual int Id { get; set; }
public virtual string Matricola { get; set; }
public virtual string Ruolo { get; set; }
public virtual IList ListaSedi { get; set; }
public Profilo()
{
ListaSedi = new List();
}
}
[Serializable]
public class Sede
{
public virtual string CodiceSede { get; set; }
public virtual string DescrizioneSede { get; set; }
public virtual IList ProfiliAssociati { get; set; }
}
And new mappings:
public class Map_Sede : FluentNHibernate.Mapping.ClassMap
{
public Map_Sede()
{
Table("TBA_Sede");
Id(x => x.CodiceSede).Column("codice_sede").GeneratedBy.Assigned();
Map(x => x.DescrizioneSede)
.Column("descrizione");
HasMany(x => x.ProfiliAssociati)
.AsBag()
.KeyColumns.Add("codice_sede")
.Cascade.All();
}
}
public class Map_Profilo : FluentNHibernate.Mapping.ClassMap
{
public Map_Profilo()
{
Table("TBA_Profilo");
Id(x => x.Id).Column("id").GeneratedBy.Identity();
Map(x => x.Matricola)
.Column("matricola");
Map(x => x.Ruolo)
.Column("ruolo");
HasMany(x => x.ListaSedi)
.AsBag()
.Inverse()
.KeyColumns.Add("codice_sede")
.Cascade.SaveUpdate();
}
}
Now it seems quite to work: i mean that nhibernate can write TBA_Profilo.codice_sede column even if it doesn't cicle on Profilo.IList (it inserts the last element of this List).
Any ideas?
KeyColumns mapping is applied only child table in many-to-one connection.
If you want to have connection you will need to use Id column from TBA_portfolio table and reference it from TBA_Sede.
Something like this:
Tba_portfolio
Id|matricola|ruolo
Tba_sede
Id|PorfolioId|descrizione
Your mapping is wrong, try this:
public class Map_Profilo : FluentNHibernate.Mapping.ClassMap
{
public Map_Profilo()
{
Table("TBA_Profilo");
Id(x => x.Id).Column("id").GeneratedBy.Identity();
Map(x => x.Matricola)
.Column("matricola");
Map(x => x.Ruolo)
.Column("ruolo");
HasMany(x => x.ListaSedi)
.AsBag()
.KeyColumns.Add("codice_sede")
.Not.LazyLoad()
.Cascade.SaveUpdate();
}
}
public class Map_Sede : FluentNHibernate.Mapping.ClassMap
{
public Map_Sede()
{
Table("TBA_Sede");
Id(x => x.CodiceSede).Column("codice_sede").GeneratedBy.Assigned();
Map(x => x.DescrizioneSede)
.Column("descrizione");
References(prof => prof.Profilo)
.Column("codice_sede")
.Cascade.None()
.Inverse();
}
}
The key is, you need the parent profilio to save its child items. Have the child items do nothing to its parent. Also, your table diagram looks wrong, profolio should not have a key to sede, but sede should have a fk to profolio.