简体   繁体   English

实体框架中仅难度映射基类

[英]Difficulty only mapping base class in Entity Framework

I'm having difficulty figuring out how to only map a base class in Entity Framework to my database, while preventing any information about classes that inherit it from being mapped to the database. 我很难弄清楚如何仅将Entity Framework中的基类映射到我的数据库,同时防止有关继承它的类的任何信息映射到数据库。

I created a simple example to highlight my difficulty where there is a base Worker class, and a child class called Engineer . 我创建了一个简单的示例来突出说明我的困难,即存在一个基本的Worker类和一个名为Engineer的子类。 For some reason, assume that I don't care to store details of the engineer... I only want my database to contain the information in the Worker class. 出于某种原因,假设我不在乎存储工程师的详细信息...我只希望我的数据库将信息包含在Worker类中。

So I've done the following: 所以我做了以下工作:

class Program
{
    static void Main(string[] args)
    {
        Engineer e = new Engineer();
        e.Name = "George";
        e.Focus = "Software";

        MyDatabase db = new MyDatabase();
        e.Save(db);
    }
}

public class MyDatabase : DbContext
{
    public DbSet<Worker> Workers { get; set; } 
    public MyDatabase() : base("mytempdb") { }
}

[NotMapped]
public class Engineer : Worker
{
    public string Focus { get; set; }
}


public class Worker
{
    [Key]
    [DatabaseGeneratedAttribute(DatabaseGeneratedOption.Identity)]
    public int ID { get; set; }
    public string Name { get; set; }

    public bool Save(MyDatabase db)
    {
        try
        {
            if (db.Workers.Any(w => w.ID == this.ID))
            {
                db.Workers.Attach(this);
                db.Entry(this).State = System.Data.Entity.EntityState.Modified;
            }
            else
            {
                db.Workers.Add((Worker)this);
            }
            db.SaveChanges();
        }
        catch (Exception e)
        {
            Console.WriteLine(e);
            return false;
        }

        return true;
    }
}

I am doing "Database First" design, and my database table looks like: 我正在做“数据库优先”设计,我的数据库表如下所示:

CREATE TABLE [dbo].Workers
(
    [ID] INT NOT NULL PRIMARY KEY, 
    [Name] NVARCHAR(200) NULL, 
    [Discriminator] NVARCHAR(200) NULL
)

However, when I run my program, it is still looking for a entity to store Engineer in. I've told it not to map it, hoping that it would only map the base class to the database: 但是,当我运行程序时,它仍在寻找要存储Engineer的实体。我告诉它不要映射它,希望它只会将基类映射到数据库:

System.InvalidOperationException: Mapping and metadata information could not be found for EntityType 'ConsoleApplication10.Engineer'. System.InvalidOperationException:找不到EntityType'ConsoleApplication10.Engineer'的映射和元数​​据信息。

I think you might have to map the entity to a new Worker entity before saving so that entity framework doesn't look for the object's sub type— Engineer . 我认为您可能必须在保存之前将实体映射到新的Worker实体,以便实体框架不会查找对象的子类型Engineer

For example: 例如:

public class Worker
{
    [Key]
    [DatabaseGeneratedAttribute(DatabaseGeneratedOption.Identity)]
    public int ID { get; set; }
    public string Name { get; set; }

    public static FromWorker(Worker worker)
    {
        // example of mapping the entity
        return new Worker
        {
            ID = worker.ID,
            Name = worker.Name,
        };
    }

    public bool Save(MyDatabase db)
    {
        try
        {
            Worker worker = Worker.FromWorker(this);

            if (db.Workers.Any(w => w.ID == worker.ID))
            {
                db.Workers.Attach(worker);
                db.Entry(worker).State = System.Data.Entity.EntityState.Modified;
            }
            else
            {
                db.Workers.Add(worker);
            }

            db.SaveChanges();
        }
        catch (Exception e)
        {
            Console.WriteLine(e);
            return false;
        }

        return true;
    }
}

EDIT: You already use [NotMapped] 编辑:您已经使用[NotMapped]
I did not see that first time sorry. 我没有看到第一次抱歉。 So i dont expect it to be in the model. 所以我不希望它出现在模型中。

There is a do not map attribute for properties and equivalent fluent api option for whole classes. 属性没有“不映射”属性,整个类没有等效的fluent api选项。

[NotMapped] 
public string BlogCode  { get;set; }

and for a POCO inside the Context 对于上下文中的POCO

public class MyDbContext : DbContext {
   protected override void OnModelCreating(DbModelBuilder modelBuilder) {

        //Tell EF not to include these in DB. Ignore these please
        // Anthing that EF picks and generates a table for that shoudl not be persisted
       // modelBuilder.Ignore<EFpleaseIgnoreMe>();
        modelBuilder.Ignore<YourType>();
    }
   }

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM