Nhibernate added duplicate column on insert - nhibernate

I'm using Fluent NHibernate. I have a class called Audit which has ItemID property. Everytime that I want to save anything in that table give me this error.
Error message:
The column name 'itemid' is specified more than once in the SET clause or column list of an INSERT. A column cannot be assigned more than one value in the same clause. Modify the clause to make sure that a column is updated only once. If this statement updates or inserts columns into a view, column aliasing can conceal the duplication in your code.
Classes
public class Audit : EntityBase
{
/*********
** Accessors
*********/
/// <summary>When the action was logged.</summary>
public virtual DateTime Date { get; set; }
/// <summary>The person who triggered the action.</summary>
public virtual BasicUser User { get; set; }
/// <summary>The name of the related group, used for filtering (e.g. idea, system-settings, site-editor)</summary>
public virtual string ItemGroup { get; set; }
/// <summary>The ID of the related entity.</summary>
public virtual int ItemID { get; set; }
/// <summary>The title of the related entity.</summary>
public virtual LocalizableString ItemTitle { get; set; }
/*********
** Public methods
*********/
/// <summary>Construct an instance.</summary>
public Audit() { }
}
Mapping:
public class AuditMapper<T> : IEntityMapper<T>
where T : Audit
{
public virtual void ExtendDomainModel(IEntityMetadata<T> metadata)
{
metadata.MapTablePerClassHierarchy<Audit, T>("`ItemGroup`");
if (!metadata.IsSubclass)
{
metadata.Map.ManyToOne(entity => entity.User, relation => relation.Column("`userid`"));
metadata.Map.Property(c => c.ItemGroup, mapper =>
{
mapper.Insert(false);
mapper.Update(false);
});
metadata.Map.Property(c => c.ItemID, mapper => mapper.Column("itemid"));
}
else
{
metadata.MapSubclass.ManyToOne(entity => entity.User, relation => relation.Column("`userid`"));
metadata.MapSubclass.Property(c => c.ItemGroup, mapper =>
{
mapper.Insert(false);
mapper.Update(false);
});
metadata.MapSubclass.Property(c => c.ItemID, mapper =>
{
mapper.Insert(false);
mapper.Update(false);
});
}
}
}
SQL Query:
INSERT INTO [brainbank].[idealink.core.audit] ([date], [userid], itemid, [itemtitle_key], [itemtitle_original], [itemid], [ItemGroup]) VALUES (#p0, #p1, #p2, #p3, #p4, #p5, 'IdeaAudit'); select SCOPE_IDENTITY()

I fix this issue in my mapper.
I changed
metadata.Map.Property(c => c.ItemID, mapper => mapper.Column("itemid"));
to
metadata.Map.Property(c => c.ItemID, mapper =>
{
mapper.Insert(false);
mapper.Update(false);
});

Related

Cannot insert explicit value for identity column in table 'Regions' when IDENTITY_INSERT is set to OFF

I have a table called Regions with an auto increment ID column. When adding data to the regions table through my ASP.NET Core application, I get this error:
Cannot insert explicit value for identity column in table 'Regions' when IDENTITY_INSERT is set to OFF.
I know why this is happening, I just don't know how to prevent EF Core from writing a value into this Id column. I have tried a few things to try and mitigate this but to no avail.
Here is my model, dbContext and the CreateRegions method. The primary key on this table is the RegionId.
Model class:
public partial class RegionsModel
{
[DisplayName("No :")]
[DatabaseGenerated(DatabaseGeneratedOption.None)]
public int Id { get; set; }
[Key]
public Guid RegionId { get; set; }
[DisplayName("Region Name :")]
public string RegionName { get; set; } = null!;
}
DbContext:
modelBuilder.Entity<RegionsModel>(entity =>
{
entity.Property(e => e.Id).ValueGeneratedNever();
entity.Property(e => e.RegionId).HasDefaultValueSql("(newid())");
entity.Property(e => e.RegionName).HasMaxLength(50);
});
Create region method:
public async Task<IActionResult> CreateRegion([Bind("Id,RegionId,RegionName")] RegionsModel regionsModel)
{
if (ModelState.IsValid)
{
_context.Add(regionsModel);
await _context.SaveChangesAsync();
return RedirectToAction(nameof(RegionsIndex));
}
return View(regionsModel);
}
You need to change two things:
(1) The data annotation on your model class needs to be [DatabaseGenerated(DatabaseGeneratedOption.Identity)] :
public partial class RegionsModel
{
[DisplayName("No :")]
[DatabaseGenerated(DatabaseGeneratedOption.Identity)]
public int Id { get; set; }
[Key]
public Guid RegionId { get; set; }
[DisplayName("Region Name :")]
public string RegionName { get; set; } = null!;
}
(2) Your OnModelCreating needs to define the column Id as being set on Add:
modelBuilder.Entity<RegionsModel>(entity =>
{
// set this to "ValueGeneratedOnAdd"
entity.Property(e => e.Id).ValueGeneratedOnAdd();
entity.Property(e => e.RegionId).HasDefaultValueSql("(newid())");
entity.Property(e => e.RegionName).HasMaxLength(50);
});
That defines Id to be an IDENTITY column in your database table, and sets up EF Core to let SQL Server add a new value "on add" (when inserting a new row into the table) to that column.

Fluent NHibernate one-to-many relationship setting foreign key to null

I have a simple Fluent NHibernate model with two related classes:
public class Applicant
{
public Applicant()
{
Tags = new List<Tag>();
}
public virtual int Id { get; set; }
//other fields removed for sake of example
public virtual IList<Tag> Tags { get; protected set; }
public virtual void AddTag(Tag tag)
{
tag.Applicant = this;
Tags.Add(tag);
}
}
public class Tag
{
public virtual int Id { get; protected set; }
public virtual string TagName { get; set; }
public virtual Applicant Applicant { get; set; }
}
My fluent mapping is the following:
public class ApplicantMap : ClassMap<Applicant>
{
public ApplicantMap()
{
Id(x => x.Id);
HasMany(x => x.Tags).Cascade.All();
}
}
public class TagMap : ClassMap<Tag>
{
public TagMap()
{
Id(x => x.Id);
Map(x => x.TagName);
References(x => x.Applicant).Not.Nullable();
}
}
Whenever I try to update an applicant (inserting a new one works fine), it fails and I see the following SQL exception in the logs:
11:50:52.695 [6] DEBUG NHibernate.SQL - UPDATE [Tag] SET Applicant_id = null WHERE Applicant_id = #p0;#p0 = 37 [Type: Int32 (0)]
11:50:52.699 [6] ERROR NHibernate.AdoNet.AbstractBatcher - Could not execute command: UPDATE [Tag] SET Applicant_id = null WHERE Applicant_id = #p0 System.Data.SqlClient.SqlException (0x80131904): Cannot insert the value NULL into column 'Applicant_id', table 'RecruitmentApp.dbo.Tag'; column does not allow nulls. UPDATE fails.
Why is NHibernate trying to update the tag table and set Applicant_id to null? I'm at a loss on this one.
Set Applicant.Tags to Inverse will instruct NHibernate to save Tags after the Applicant.
public class ApplicantMap : ClassMap<Applicant>
{
public ApplicantMap()
{
Id(x => x.Id);
HasMany(x => x.Tags).Cascade.All().Inverse();
}
}
More detail:
Inverse (as opposed to .Not.Inverse()) means the other side of the relationship (in this case, each Tag) is responsible for maintaining the relationship. Therefore, NHibernate knows that the Applicant must be saved first so that Tag has a valid foreign key for its Applicant.
Rule of thumb: The entity containing the foreign key is usually the owner, so the other table should have Inverse

FluentNHibernate and persistence of tree structure

I have an application storing a tree structure and is able to generate the database fine, but when inserting I get an exception. I simplified the code to narrow down the problem.
The class to be saved:
public class Node
{
public virtual int NodeId { get; set; }
public virtual string Name { get; set; }
public virtual Node Parent { get; set; }
public virtual IList<Node> Children { get; set; }
}
This is the mapper code:
public sealed class NodeMap : ClassMap<Node>
{
public NodeMap()
{
Id(n => n.NodeId).GeneratedBy.Identity();
Map(n => n.Name);
References(n => n.Parent).LazyLoad().Nullable();
HasMany(n => n.Children).LazyLoad().KeyColumn("ParentId");
}
}
When I do an insert like dataClient.Insert(new Node { Name = "Test" }); I get an exception saying:
NHibernate.Exceptions.GenericADOException: could not insert: [Model.Node][SQL: INSERT INTO [Node] (Name, NodeId) VALUES (?, ?); select SCOPE_IDENTITY()]
And the inner exception says:
System.Data.SqlClient.SqlException: Cannot insert explicit value for identity column in table 'Node' when IDENTITY_INSERT is set to OFF.
Which is actually perfectly understandable, but I just wonder why it is trying to set an explicit value for NodeId. When I remove the References part, the insert goes through, so it must be related to that somehow.
The version of FluentNHibernate is 1.2.0.712 and the version of NHibernate is 3.1.0.4000.
it is because the default column is typename + id for the reference which happens to be the same name as the id column. Explicitly state it in the reference.
References(n => n.Parent, "ParentId").LazyLoad().Nullable();
Update: as convention
public class ReferenceColumnConvention : IReferenceConvention
{
public void Apply(IManyToOneInstance instance)
{
// uncomment if needed
//if (instance.EntityType == instance.Property.PropertyType)
instance.Column(instance.Name + "id");
}
}

Batch Update, Delete, Insert not work correctly with version control

I'm using Nhibernate 3.2 and fluent nhibernate, I have two tables Customer Group and Customer, and I use for lock management version control with TimeStamp Column.
I have the following classes and maps for these classes:
public class Customer
{
public Customer()
{
}
public virtual int CustomerID { get; set; }
public virtual CustomerGroup customerGroup { get; set; }
public virtual int CustomerGroupID { get; set; }
public virtual string CustomerRef { get; set; }
public virtual string NameE { get; set; }
public virtual string NameA { get; set; }
public virtual byte[] TimeStamp { get; set; }
}
and his map
public class CustomerMap : ClassMap<Customer> {
public CustomerMap() {
Table("Customer");
Id(x => x.CustomerID).GeneratedBy.Identity().Column("CustomerID");
Version(x =>x.TimeStamp).CustomType("BinaryBlob").Generated.Always().Column("TimeStamp");
DynamicUpdate();
OptimisticLock.Version();
References(x =>x.customerGroup).Column("CustomerGroupID").ForeignKey("CustomerGroupID");
Map(x => x.CustomerRef).Column("CustomerRef").Length(30).Unique();
Map(x => x.NameE).Column("NameE").Not.Nullable().Length(100).Unique();
Map(x => x.NameA).Column("NameA").Length(100);
and for Customer Group:
public class CustomerGroup {
public CustomerGroup() {
Customers = new List<Customer>(3);
}
public virtual int CustomerGroupID { get; set; }
public virtual IList<Customer> Customers { get; set; }
public virtual byte[] TimeStamp { get; set; }
}
and his map:
public CustomerGroupMap() {
Table("CustomerGroup");
Version(x => x.TimeStamp).CustomType("BinaryBlob").Generated.Always().Column("TimeStamp");
DynamicUpdate();
OptimisticLock.Version();
Id(x => x.CustomerGroupID).GeneratedBy.Identity().Column("CustomerGroupID");
HasMany(x => x.Customers).KeyColumn("CustomerGroupID");
}
When I create update in list of customers belong to specific Customer Group like this:
ISession Session = OpenSession();
Session.BeginTransaction();
var customerGroupInfo = Session.Query<CustomerGroup>().Fetch(x => x.Customers).Single<CustomerGroup>(x => x.CustomerGroupID == 98);
foreach (var item in customerGroupInfo.Customers)
{
item.NameE = "abc";
Session.Update(item);
}
Session.Transaction.Commit();
apply these sql statements:
UPDATE Customer SET NameE = 'abc'
WHERE CustomerID = 200 AND TimeStamp = 0x00000000000092EF
SELECT customer_.TimeStamp as TimeStamp1_ FROM Customer customer_
WHERE customer_.CustomerID = 200
UPDATE Customer SET NameE = 'abc'
WHERE CustomerID = 201 AND TimeStamp = 0x00000000000092F0
SELECT customer_.TimeStamp as TimeStamp1_ FROM Customer customer_
WHERE customer_.CustomerID = 201
.
.
.
and every update and every select operate in single round trip.
I set property adonet.batch_size property in configuration like this:
<property name="adonet.batch_size">20</property>
I read in this post this behavior founded by default in Nhibernate 3.2.
Any Tips to make batch work correctly?
You might look at changing your Session.FlushMode to something other than Automatic. That way, you could do something like this:
Session.FlushMode = NHibernate.FlushMode.Never
foreach (var item in customerGroupInfo.Customers)
{
item.NameE = "abc";
Session.Update(item);
}
Session.Flush();
Session.Transaction.Commit();
// Perhaps changing the flushmode after commit?
Session.FlushMode = NHibernate.FlushMode.Auto;
Edit :
Nevermind, see this excerpt from the docs: http://nhibernate.info/doc/nh/en/index.html#batch
It appears that batching doesn't get along with optimistic locking.
NHibernate supports batching SQL update commands (INSERT, UPDATE, DELETE) with the following limitations:
.NET Framework 2.0 or above is required,
**the Nhibernate's drive used for your RDBMS may not supports batching,**
since the implementation uses reflection to access members and types in System.Data assembly which are not normally visible, it may not function in environments where necessary permissions are not granted
**optimistic concurrency checking may be impaired since ADO.NET 2.0 does not return the number of rows affected by each statement in the batch, only the total number of rows affected by the batch.**

HNibernate 1 to Many Relationship Fluent NHiberate using only the Foreign Key Id

I'm wanting to have a 1 to many relationship in NHibernate where the Child table only has access to it's parentsId. Or the foreign key in the DB.
I've tried the following setup:
public class ParentTable
{
public ParentTable()
{
_childRecords = new List<ChildTable>();
}
public virtual int ParentId { get; set; }
private IList<ChildTable> _childRecords;
public virtual IEnumerable<ChildTable> ChildRecords
{
get { return _childRecords; }
}
public void AddChildTable(string value)
{
_childRecords.Add(new ChildTable{ StringField = value });
}
}
public class ChildTable
{
public virtual int ChildTableId { get; set; }
public virtual string StringField { get; set; }
public virtual int ParentId { get; set; }
}
Mappings:
public class ParentTableMap : ClassMap<ParentTable>
{
public ParentTableMap()
{
Not.LazyLoad();
Id(x => x.ParentId);
HasMany(x => x.ChildRecords)
.Not.LazyLoad()
.KeyColumn("ParentId").Cascade.All()
.Access.ReadOnlyPropertyThroughCamelCaseField(Prefix.Underscore);
}
}
public class ChildTableMap : ClassMap<ChildTable>
{
public ChildTableMap()
{
Not.LazyLoad();
Id(x => x.ChildTableId);
Map(x => x.StringField);
Map(x => x.ParentId).Not.Nullable();
}
}
The following test fails as it's trying to insert 0 into the ParentId column?
[TestFixture]
public class Tests
{
[Test]
public void SaveOrUpdate_ParentWithChildren_WillCreateParentWithChildRecordsHavingMatchingParentId()
{
int id;
using (var sessionForInsert = SessionProvider.SessionFactory.OpenSession())
{
using (var trx = sessionForInsert.BeginTransaction())
{
//Assign
var parent = new ParentTable();
parent.AddChildTable("Testing");
parent.AddChildTable("Testing2");
sessionForInsert.SaveOrUpdate(parent); // Fails here with DB constraint error
id = parent.ParentId;
}
}
using (var sessionForSelect = SessionProvider.SessionFactory.OpenSession())
{
//Action
var result = sessionForSelect.Get<ParentTable>(id);
Assert.AreEqual(id, result.ParentId);
Assert.AreEqual(id, result.ChildRecords.First().ParentId);
Assert.AreEqual(id, result.ChildRecords.Last().ParentId);
}
}
}
This is what it's trying to do:
exec sp_executesql N'INSERT INTO ChildTable (StringField, ParentId) VALUES (#p0, #p1); select SCOPE_IDENTITY()',N'#p0 nvarchar,#p1 int',#p0='Testing;,#p1=0
I realise I could set-up a reference to the Parent Class in the Child Class. However I'd like to avoid this if at all possible, due to circular references and the problems that will cause when serializing and de-serializing these classes.
Has anyone successfully set-up and 1 to many relationship like the above?
Thanks
Dave
I think you either need to:
Make the ParentId on ChildTable nullable, or
Change your id generators to something NHibernate can generate.
The second option is nice. Switch to Guid.Comb for your id's. There's a restriction on what object relational mappers can do. Specifically, it is recommended to let NHibernate generate the id's instead of the database. I think this (long) blog post explains it in detail: http://fabiomaulo.blogspot.com/2009/02/nh210-generators-behavior-explained.html.
Good luck!
The problem is that you are attempting to insert a parent and its children in one operation. To do this, NHibernate wants to insert the child records with a null ParentId then update ParentId after the parent record is inserted. This foreign key constraint causes this to fail.
The best solution is to map the relationship from child to parent. You don't have to publicly expose the parent, you could just expose its ParentId as int? if desired.
If that's unacceptable, you should be able to accomplish this by changing the order of operations. First, I would require the ParentId in ChildTable's constructor. Then change the operation order in the test to get it to pass.
public class ChildTable
{
public ChildTable(int parentId) { ParentId = parentId; }
public virtual int ChildTableId { get; set; }
public virtual string StringField { get; set; }
public virtual int ParentId { get; private set; }
}
using (var trx = sessionForInsert.BeginTransaction())
{
//Assign
var parent = new ParentTable();
sessionForInsert.Save(parent);
sessionForInsert.Flush(); // may not be needed
parent.AddChildTable("Testing");
parent.AddChildTable("Testing2");
trx.Commit();
id = parent.ParentId;
}
EDIT:
public class ChildTable
{
private ParentTable _parent;
public ChildTable(Parent parent) { _parent = parent; }
public virtual int ChildTableId { get; set; }
public virtual string StringField { get; set; }
public virtual int? ParentId
{
get { return _parent == null : null ? _parent.ParentId; }
}
}
public class ChildTableMap : ClassMap<ChildTable>
{
public ChildTableMap()
{
Not.LazyLoad();
Id(x => x.ChildTableId);
Map(x => x.StringField);
// From memory, I probably have this syntax wrong...
References(Reveal.Property<ParentTable>("Parent"), "ParentTableId")
.Access.CamelCaseField(Prefix.Underscore);
}
}