【问题标题】:How to do a fluent nhibernate one to one mapping?如何进行流畅的 nhibernate 一对一映射?
【发布时间】:2011-08-30 10:40:05
【问题描述】:

我该怎么做我正在尝试进行一对一的映射。

public class Setting
{
    public virtual Guid StudentId { get; set; }
    public virtual DateFilters TaskFilterOption { get; set; }
    public virtual string TimeZoneId { get; set; }
    public virtual string TimeZoneName { get; set; }
    public virtual DateTime EndOfTerm { get; set; }
    public virtual Student Student { get; set; }

}

//类映射

 public SettingMap()
        {
           /// Id(Reveal.Member<Setting>("StudentId")).GeneratedBy.Foreign("StudentId");
            //Id(x => x.StudentId);
            Map(x => x.TaskFilterOption).Default(DateFilters.All.ToString()).NvarcharWithMaxSize().Not.Nullable();
            Map(x => x.TimeZoneId).NvarcharWithMaxSize().Not.Nullable();
            Map(x => x.TimeZoneName).NvarcharWithMaxSize().Not.Nullable();
            Map(x => x.EndOfTerm).Default("5/21/2011").Not.Nullable();
            HasOne(x => x.Student);
        }

//学生地图

public class StudentMap : ClassMap<Student>
    {
        public StudentMap()
        {
            Id(x => x.StudentId);
            HasOne(x => x.Setting).Cascade.All();

        }
    }

  public class Student
    {
        public virtual Guid StudentId { get; private set; }
        public virtual Setting Setting { get; set; }
    }

现在每次我尝试创建设置对象并将其保存到数据库时都会崩溃。

   Setting setting = new Setting
                                          {
                                              TimeZoneId = viewModel.SelectedTimeZone, 
                                              TimeZoneName = info.DisplayName, 
                                              EndOfTerm =  DateTime.UtcNow.AddDays(-1),
                                              Student = student
                                          };

The INSERT statement conflicted with the FOREIGN KEY constraint "FK_Settings_Students". The conflict occurred in database "Database", table "dbo.Students", column 'StudentId'.
The statement has been terminated.
Description: An unhandled exception occurred during the execution of the current web request. Please review the stack trace for more information about the error and where it originated in the code.

Exception Details: System.Data.SqlClient.SqlException: The INSERT statement conflicted with the FOREIGN KEY constraint "FK_Settings_Students". The conflict occurred in database "Database", table "dbo.Students", column 'StudentId'.
The statement has been terminated.

我错过了什么?

编辑

public class StudentMap : ClassMap<Student>
{
    public StudentMap()
    {
        Id(x => x.StudentId).GeneratedBy.Guid();
        HasOne(x => x.Setting).PropertyRef("Student").Cascade.All();
    }
}

public class SettingMap : ClassMap<Setting>
{
    public SettingMap()
    {
        Id(x => x.StudentId).GeneratedBy.Guid();
        Map(x => x.TaskFilterOption).Default(DateFilters.All.ToString()).NvarcharWithMaxSize().Not.Nullable();
        Map(x => x.TimeZoneId).NvarcharWithMaxSize().Not.Nullable();
        Map(x => x.TimeZoneName).NvarcharWithMaxSize().Not.Nullable();
        Map(x => x.EndOfTerm).Default("5/21/2011").Not.Nullable();
        References(x => x.Student).Unique();
    }
}

// try 1

      Setting setting = new Setting
                                          {
                                              TimeZoneId = viewModel.SelectedTimeZone, 
                                              TimeZoneName = info.DisplayName, 
                                              EndOfTerm =  DateTime.UtcNow.AddDays(-1),
                                              Student = student
                                          };
     studentRepo.SaveSettings(setting);
     studentRepo.Commit();

// try 2

  Setting setting = new Setting
                                          {
                                              TimeZoneId = viewModel.SelectedTimeZone, 
                                              TimeZoneName = info.DisplayName, 
                                              EndOfTerm =  DateTime.UtcNow.AddDays(-1),
                                              Student = student
                                          };

student.Setting = setting
studentRepo.CreateStudent(student);
studentRepo.Commit();

两种方式都出现这些错误

Invalid index 5 for this SqlParameterCollection with Count=5. Description: An unhandled exception occurred during the execution of the current web request. Please review the stack trace for more information about the error and where it originated in the code.

Exception Details: System.IndexOutOfRangeException: Invalid index 5 for this SqlParameterCollection with Count=5.

Source Error:

Line 76:             using (ITransaction transaction = session.BeginTransaction()) Line 77:   { Line 78:                 transaction.Commit(); Line 79:         } Line 80:         }

【问题讨论】:

    标签: c# nhibernate fluent-nhibernate


    【解决方案1】:

    在 NH 中映射双向一对一关联有两种基本方法。假设类如下所示:

    public class Setting
    {
        public virtual Guid Id { get; set; }
        public virtual Student Student { get; set; }
    }
    
    public class Student
    {
        public virtual Guid Id { get; set; }
        public virtual Setting Setting { get; set; }
    }
    

    设置类是关联中的主人(“聚合根”)。这很不寻常,但取决于问题领域...

    主键关联

    public SettingMap()
    {
        Id(x => x.Id).GeneratedBy.Guid();
        HasOne(x => x.Student).Cascade.All();
    }
    
    public StudentMap()
    {
        Id(x => x.Id).GeneratedBy.Foreign("Setting");
        HasOne(x => x.Setting).Constrained();
    }
    

    并且应该存储一个新的设置实例:

            var setting = new Setting();
    
            setting.Student = new Student();
            setting.Student.Name = "student1";
            setting.Student.Setting = setting;
            setting.Name = "setting1";
    
            session.Save(setting);
    

    外键关联

    public SettingMap()
    {
        Id(x => x.Id).GeneratedBy.Guid();
        References(x => x.Student).Unique().Cascade.All();
    }
    
    public StudentMap()
    {
        Id(x => x.Id).GeneratedBy.Guid();
        HasOne(x => x.Setting).Cascade.All().PropertyRef("Student");
    }
    

    主键关联接近您的解决方案。仅当您绝对确定关联将始终是一对一的时,才应使用主键关联。请注意,在 NH 中一对一不支持 AllDeleteOrphan 级联。

    编辑:有关详细信息,请参阅:

    http://fabiomaulo.blogspot.com/2010/03/conform-mapping-one-to-one.html

    http://ayende.com/blog/3960/nhibernate-mapping-one-to-one

    【讨论】:

    • 嗯,这很奇怪。我从未见过这样的例外。它有任何内部异常吗?您是否使用任何侦听器或拦截器?
    • 可能问题在于 Setting 类中有两个属性映射到一列:学生参考和 StudentId 属性。请参阅:stackoverflow.com/questions/388914/…。
    • 我刚刚创建了一个示例项目,其中“表 A”有一个主键,“表 B”有一个主键,它也是“表 A”的外键。 外键关联在这种情况下效果很好。要记住的重要一点是您的“表 B”映射​​需要分别映射主键值和 HasOne 关联。
    • PropertyRef 是什么意思?
    【解决方案2】:

    这里是带有外键关联的完整示例

    using System;
    using FluentNHibernate.Cfg;
    using FluentNHibernate.Cfg.Db;
    using NHibernate;
    using FluentNHibernate.Mapping;
    
    namespace NhOneToOne
    {
        public class Program
        {
            static void Main(string[] args)
            {
                try
                {
    
                    var sessionFactory = Fluently.Configure()
                                                 .Database(
                                                        MsSqlConfiguration.MsSql2005
                                                                          .ConnectionString(@"Data Source=(localdb)\MSSQLLocalDB;Initial Catalog=NHTest;Integrated Security=True;Connect Timeout=30;Encrypt=False;TrustServerCertificate=True;ApplicationIntent=ReadWrite;MultiSubnetFailover=False")
                                                                          .ShowSql()
                                                  )
                                                 .Mappings(m => m
                                                 .FluentMappings.AddFromAssemblyOf<Program>())
                                                 .BuildSessionFactory();
    
                    ISession session = sessionFactory.OpenSession();
    
    
                    Parent parent = new Parent();
                    parent.Name = "test";
                    Child child = new Child();
                    child.Parent = parent;
                    parent.Child = child;
                    session.Save(parent);
                    session.Save(child);
    
                    int id = parent.Id;
                    session.Clear();
                    parent = session.Get<Parent>(id);
                    child = parent.Child;
    
    
                }
                catch (Exception e)
                {
                    Console.Write(e.Message);
                }
            }
    
        }
    
        public class Child
        {
            public virtual string Name { get; set; }
            public virtual int Id { get; set; }
    
            public virtual Parent Parent { get; set; }
        }
    
        public class Parent
        {
            public virtual string Name { get; set; }
            public virtual int Id { get; set; }
    
            public virtual Child Child { get; set; }
    
        }
    
        public class ChildMap : ClassMap<Child>
        {
            public ChildMap()
            {
                Table("ChildTable");
                Id(x => x.Id).GeneratedBy.Native();
                Map(x => x.Name);
    
                References(x => x.Parent).Column("IdParent");
    
            }
        }
    
        public class ParentMap : ClassMap<Parent>
        {
            public ParentMap()
            {
                Table("ParentTable");
                Id(x => x.Id).GeneratedBy.Native();
                Map(x => x.Name);
    
                HasOne(x => x.Child).PropertyRef(nameof(Child.Parent));
            }
    
        }
    }
    

    以及创建表的 SQL

    CREATE TABLE [dbo].[ParentTable] (
        [Id]   INT           IDENTITY (1, 1) NOT NULL,
        [Name] VARCHAR (MAX) NULL
    );
    CREATE TABLE [dbo].[ChildTable] (
        [Id]       INT          IDENTITY (1, 1) NOT NULL,
        [IdParent] INT          NOT NULL,
        [Name]     VARCHAR (50) NULL
    );
    ALTER TABLE [dbo].[ChildTable]
        ADD CONSTRAINT [FK_ChildTable_ToTable] FOREIGN KEY ([IdParent]) REFERENCES [dbo].[ParentTable] ([Id]);
    

    【讨论】:

      【解决方案3】:

      首先,将关系的一侧定义为 Inverse(),否则数据库中存在冗余列,这可能会导致问题。

      如果这不起作用,输出NHibernate生成的SQL语句(使用ShowSql或通过log4net)并尝试了解为什么违反外键约束(或将其与SQL一起发布在这里,不要忘记出现在 SQL 语句之后的绑定变量的值)。

      【讨论】:

        【解决方案4】:

        您不应在 Sesstings 类中定义 StudentId。 Sesting 类已经有了它(来自 public virtual Student Student { get; set; })。可能它应该是 SesstingId 并且您也应该映射 Id 字段(您必须定义/映射主键)。

        【讨论】:

        • 如果我从设置中删除 StudentId,流利的 nhibernate 将崩溃并且对于 PK
        猜你喜欢
        • 1970-01-01
        • 2011-11-17
        • 2023-03-14
        • 2010-11-22
        • 1970-01-01
        • 2010-10-09
        • 1970-01-01
        • 2013-11-14
        • 1970-01-01
        相关资源
        最近更新 更多