【问题标题】:linq to sql only parent being inserted into dblinq to sql 只有父级被插入到数据库中
【发布时间】:2011-04-13 03:25:06
【问题描述】:

大家好,我有一个问题,只有我的父母被插入到数据库中,我错过了什么吗?这是我的代码sn-p

public partial class linqtest : System.Web.UI.Page
    {
        protected void Page_Load(object sender, EventArgs e)
        {
            MyContext db = new MyContext("Server=(local);Database=Test;User ID=admin;Password=pw");
            Child c = new Child();
            c.name = "joe "+DateTime.Now;
            db.parents.InsertOnSubmit(c);
            db.SubmitChanges();
        }
    }

    public class MyContext : DataContext
    {
        public static DataContext db;
        public MyContext(string connection) : base(connection) { }
        public Table<Parent> parents;
    }

    [Table(Name="parents")]
    [InheritanceMapping(Code = "retarded", Type = typeof(Child), IsDefault=true)]
    public class Parent
    {
        [Column(Name = "id", IsPrimaryKey = true, CanBeNull = false, DbType = "Int NOT NULL IDENTITY", IsDbGenerated = true)] /* I want this to be inherited by subclasses */
        public int id { get; set; }

        [Column(Name = "name", IsDiscriminator = true)] /* I want this to be inherited by subclasses */
        public string name { get; set; }
    }

    public class Child : Parent
    {

    }

【问题讨论】:

  • 您能否澄清插入后数据库中parents 表中的内容? ChildParent 都被持久化到同一个表(parents),所以不清楚你的意思是只有父级被保存。你得到了什么,你期望得到什么?
  • 对不起,缺少信息,在父母表中我得到了 id:(由 SQL 自动递增),名称:“延迟”,我有另一个表孩子,我想把它与班级联系起来孩子。但是是的,我还没有将它集成到其中,因为我不知道如何:-/我试图将 [Table] 添加到 calss Child 但它出错,因为我定义了 2 个根 heirachys。编辑:废话!!对不应该存在的迟钝的东西感到抱歉
  • 这是你的问题,不幸的是......答案即将到来。 :-)

标签: linq-to-sql


【解决方案1】:

您所描述的其中有一个表用于父对象,另一个表用于子对象称为“多表继承”或“每个子类型的表”......不幸的是,Linq 不支持它到 SQL。请参阅 SO 问题 Multiple Inheritance in LINQtoSQL? 和我自己的问题,在 Simulating Multiple Table Inheritance in Linq-to-SQL 寻找解决方法。您也可以谷歌“linq-to-sql 中的表继承”,了解如何在 Linq-to-SQL 中进行单表继承,这是支持的。

【讨论】:

  • 哦,我明白了!!!!!!!!!非常感谢您的回复,这真的很有帮助。 :)!现在我不确定我是否会去实体框架,我想我想但刚刚学习了 LINQ2SQL 并且不确定我是否会为重新学习实体而烦恼。对我来说,单表继承的问题是我的表中有很多记录,可能是 100K,希望将内容放在单独的表中以缩短搜索时间。我会大量索引,但如果我留在一个表中,我的查找可能会变得太慢:-(
  • 是的,我自己对此并不满意,这也是我努力寻找替代方案的原因。 必须有一种方法可以相对轻松地做到这一点....
猜你喜欢
  • 2015-12-17
  • 2011-01-29
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2016-08-23
  • 1970-01-01
相关资源
最近更新 更多