0

我不知道如何解决以下问题。我需要它从一个基类到另一个基类的关系,以便每个派生类都与同一个表有关系,在我的示例中称为“项目”。

由于这只是一个示例,它不反映我的程序。在实际程序中,与类 Item 的关系位于不同的命名空间中。因此它不能在派生类中。

错误:

为派生类型“WebApplication1.Client”注册了一个密钥。必须为根类型“WebApplication1.Base”注册密钥。

namespace WebApplication1
{
    public class Item
    {
        public int ItemID { get; set; }
    }

    public class Base
    {
        public int ID { get; set; }
        public int ItemID { get; set; }

        public Item Item { get; set; }

    }

    public class Client : Base
    {
        public string Name { get; set; }

        private List<Project> _projects = null;

        public List<Project> Projects
        {
            get
            {
                if (_projects == null)
                    _projects = new List<Project>();

                return _projects;
            }
        }
    }

    public class Project : Base
    {
        public string Name { get; set; }

        public int ClientId { get; set; }

        public Client Client { get; set; }

    }

    public class Main
    {
        public static void Test()
        {
            ContextBuilder<ObjectContext> ContextBuilder = new ContextBuilder<ObjectContext>();

            var itemConfig = new EntityConfiguration<Item>();
            itemConfig.HasKey(p => p.ItemID);
            itemConfig.Property(p => p.ItemID).IsIdentity();
            ContextBuilder.Configurations.Add(itemConfig);

            var clientConfig = new EntityConfiguration<Client>();
            clientConfig.HasKey(p => p.ID);
            clientConfig.Property(p => p.ID).IsIdentity();
            clientConfig.Property(p => p.Name);
            clientConfig.Relationship(p => p.Item).HasConstraint((p, c) => p.ItemID == c.ItemID);           
            ContextBuilder.Configurations.Add(clientConfig);

            var projectConfig = new EntityConfiguration<Project>();
            projectConfig.HasKey(p => p.ID);
            projectConfig.Property(p => p.ID).IsIdentity();
            projectConfig.Property(p => p.Name);

            projectConfig.Relationship(p => p.Item).HasConstraint((p, c) => p.ItemID == c.ItemID);

            projectConfig.Relationship(p => p.Client).FromProperty(p => p.Projects).HasConstraint((p, c) => p.ClientId == c.ID);

            ObjectContext objCtx = ContextBuilder.Create(new SqlConnection(@"Data Source=(local);Initial Catalog=testa;Integrated Security=SSPI;"));

            if (!objCtx.DatabaseExists())
                objCtx.CreateDatabase();

        }    
    }       
}
4

1 回答 1

0

看看这里如何处理继承映射:http: //blogs.msdn.com/b/efdesign/archive/2009/10/12/code-only-further-enhancements.aspx

对于基本的非关系探测和如何重用它们:https ://danielwertheim.wordpress.com/2009/11/29/entity-framework-4-how-to-reuse-mappings-and-add-a-concurrency -令牌/

于 2010-07-01T05:28:44.627 回答