Fluent NHibernate Adding and Updating problem : References

☆樱花仙子☆ 提交于 2019-12-14 04:07:06

问题


Im fairly n00bish when it comes to fluent nhibernate but i have an unexpected error in one of my repositories.

I have a datatype CostCode

public class CostCode
{
    public virtual int Id { get; set; }
    public virtual String CostCodeCode { get; set; }
    public virtual Company Company { get; set; }
    public virtual DateTime CreatedDate { get; set; }
    public virtual String CreatedBy { get; set; }
    public virtual DateTime ModifiedDate { get; set; }
    public virtual String ModifiedBy { get; set; }
}

and here is the mapping

public sealed class CostCodeMap : ClassMap<CostCode>
{
    /**
     * @breif Mapping Constructor
     */

    public CostCodeMap()
    {
        Id(Reveal.Member<CostCode>("Id"));
        Map(x => x.CostCodeCode).Not.Nullable();
        References(x => x.Company, "CompanyId").Cascade.All();
        Map(x => x.CreatedDate).Not.Nullable();
        Map(x => x.CreatedBy).Not.Nullable();
        Map(x => x.ModifiedDate).Not.Nullable();
        Map(x => x.ModifiedBy).Not.Nullable();
    }
}

When i try to update this, i get an error "identifier of an instance of Domain.DataTypes.Company was altered from 1 to 8"

Now i think its the way that i set up the mapping, and possibly how my repository is handling the updates/adds.

I have a drop down list that controls the id of the company, and when im adding/updating i set the property company to whatever is in the database for the id that it has been updated to.

var companyRepository= new CompanyRepository(_session);
temp.Company = companyRepository.GetCompanyById(temp.Company.Id);

_session.Update(c);                

Can anyone give me a hint/solution to help me on my way? Looking through related problems here, the problem could be anything.


回答1:


Ok, I will just throw this out... I bet what is happening is you are setting temp.Company.Id by changing the Id, then you use the repo to go fetch that company using the changed Id. NHibernate will track that you changed the Id on the other company however. Use a temp var to store that new company id, dont change the id of the other company.




回答2:


I'm not 100% sure, but it really looks like maybe there is a bug here:

temp.Company = ...(temp.Company.Id);

I would figure you'd actually be pulling that from an incoming parameter.

Also, you can avoid a database hit here by using Session.Load():

temp.Company = _session.Load<Company>(passedInCompanyId);


来源:https://stackoverflow.com/questions/3990497/fluent-nhibernate-adding-and-updating-problem-references

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!