nhibernate not saving foreign key Id

前端 未结 5 789
没有蜡笔的小新
没有蜡笔的小新 2021-02-04 19:26

I have a simple model I\'m attempting to persist using fluent-nhibernate:

public class Person
{
    public int Id { get; set; }
    public string Name { get; set         


        
5条回答
  •  抹茶落季
    2021-02-04 20:21

    You need to use References. I'm not familiar with IAutoMappingOverride, but this is how I do it in manual mapping, notice the AnswerMap's References on Question:

    public class QuestionMap : ClassMap
    {
        public QuestionMap()
        {
            Id(x => x.QuestionId).GeneratedBy.Sequence("question_seq");
    
            Map(x => x.TheQuestion).Not.Nullable();
    
            HasMany(x => x.Answers).Inverse().Not.LazyLoad().Cascade.AllDeleteOrphan();
        }
    }
    
    public class AnswerMap : ClassMap
    {
        public AnswerMap()
        {
            References(x => x.Question);
    
            Id(x => x.AnswerId).GeneratedBy.Sequence("answer_seq");
    
            Map(x => x.TheAnswer).Not.Nullable();
        }
    }
    


    Model here:

    public class Question
    {
        public virtual int QuestionId { get; set; }
    
        public virtual string TheQuestion { get; set; }        
    
        public virtual IList Answers { get; set; }
    }
    
    public class Answer
    {
        public virtual Question Question { get; set; }
    
        public virtual int AnswerId { get; set; }
    
        public virtual string TheAnswer { get; set; }                
    }
    

    Note that we didn't use public virtual int QuestionId { get; set; } on Answer class, we should use public virtual Question Question { get; set; } instead. That way is more OOP, it's basically clear how your domain model looks like, free from the cruft of how objects should relate to each other(not by int, not by string, etc; but by object references)

    To allay your worries, loading object (via session.Load) doesn't incur database roundtrip.

    var answer = new Answer {
       // session.Load does not make database request
       Question = session.Load(primaryKeyValueHere), 
    
       TheAnswer = "42"
    };
    

提交回复
热议问题