1

我正在尝试创建一个简单的数据库以在 Windows Phone 应用程序中使用 sqlce。我有一个基类,以及从它派生的另一组类这就是我得到的

public abstract class EntityBase : INotifyPropertyChanged
    {
        public event PropertyChangedEventHandler PropertyChanged;

        public void OnPropertyChanged(string property)
        {
            if (PropertyChanged != null)
            {
                PropertyChanged(this, new PropertyChangedEventArgs(property));
            }
        }

        private int id;

        [Column(IsPrimaryKey = true, IsDbGenerated = true, DbType = "INT NOT NULL Identity", CanBeNull = false, AutoSync = AutoSync.OnInsert)]
        public int EntityId
        {
            get
            {
                return id;
            }
            set
            {
                if (id != value)
                {
                    id = value;
                    OnPropertyChanged("Id");
                }
            }
        }
    }

    [Table]
    public class Derived : EntityBase 
    {
        [Column]
        public string Description
        {
            get;
            set;
        }
    }

然后,我有这个类用于数据上下文:

public class MyDataContext : DataContext
    {
        // Specify the connection string as a static, used in main page and app.xaml.
        public static string DBConnectionString = "Data Source=isostore:/ToDo.sdf";

        // Pass the connection string to the base class.
        public MyDataContext(string connectionString)
            : base(connectionString)
        { }

        public Table<Derived> Deriveds;
    }

最后,我在这里尝试创建数据库:

private void Application_Launching(object sender, LaunchingEventArgs e)
        {
            using (MyDataContext db = new MyDataContext(MyDataContext.DBConnectionString))
            {
                if (db.DatabaseExists() == false)
                {
                    //Create the database -> here's the error
                    db.CreateDatabase();
                }
            }
        }

尝试创建数据库时出现以下错误:

列 ID 无效。[实体标识]

是的,一个非常描述性的错误消息......关于什么是错的任何想法?我一直在篡改列中的属性,但无济于事。

[编辑]:对于我一直在测试的内容,如果我将 EntityId 属性放在派生类中,它不会崩溃。这可能是两件事。一是我在基类中缺少其他内容,另一件事是主键的列属性必须属于该类,并且不能属于父类(将是一个非常可怕的设计决定,我们不能使用继承???)。如果有人可以确认这一点,将不胜感激

4

1 回答 1

3

好的,我想我发现了正在发生的事情。在这个 SQLCe 的实现中,我们在使用继承时需要做如下的处理:

http://msdn.microsoft.com/en-us/library/bb399352(v=VS.100).aspx

我不是特别喜欢它,它生成的表没有被规范化,但是,确实我们不应该为 WP7 应用程序使用庞大而复杂的数据存储,更多的是存储一些太多的基本信息通过自身的隔离存储来处理。按照这种方法,它起作用了。我现在有一个基类的集合,我可以将它的任何派生子类放入其中。然后为了取回它们,我在 linq to sql 查询中使用鉴别器来获取一个或另一个派生类。

于 2011-09-04T11:59:03.977 回答