开发者

Fluent NHibernate Adding and Updating problem : References

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 da开发者_如何学编程tabase 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.


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.


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);
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜