问题描述
这类似于问题此处和此处,但这些文件已过时并且没有任何用处答案.
This is similar to questions here and here, but those are old and have no good answers.
假设我有以下课程:
class HairCutStyle {
public int ID { get; set; }
public string Name { get; set; }
}
class CustomerHairCutPreference {
public int ID { get; set; }
public Customer Customer { get; set; }
public HairCutStyle HairCutStyle { get; set; }
}
比方说,我的HairCutStyle数据存储在另一个数据库的表中(我从Paul Mitchell自己得到).我想将HairCutStyle类用作POCO类-我将在代码中使用该类来表示理发样式,但无需在数据库中读取/写入该信息. (假设我有一个单独的服务层,可以从另一个数据库填充这些类的数据.)
Let's say my HairCutStyle data is stored in a table in another database (I get it from Paul Mitchell himself). I want to use the HairCutStyle class as a POCO class - something that I will use in code to represent hair cut styles, but I don't need to read/write that information in my database. (Assume I have a separate service layer that can populate the data for these classes from the other database.)
如何告诉EF不要在当前数据库上下文中创建HairCutStyle表?但同时,我想在CustomerHairCutPreference表中存储一个值,该值是对存储在其他位置的HairCutStyle数据的引用.某种虚拟"外键,不受实际数据库FK约束的约束.
How can I tell EF NOT to create a HairCutStyle table in my current db context? But at the same time, I want to store a value in the CustomerHairCutPreference table that is a reference to the HairCutStyle data stored elsewhere. A "virtual" foreign key of sorts, that isn't constrained by an actual database FK constraint.
推荐答案
要确保三件事:
- 确保您没有在
DbContext
派生类中公开DbSet<HairCutStyle>
- 确保您在
OnModelCreating
替代项中没有提及HairCutStyle
- 使用
NotMapped
属性标记您的HairCutStyle
属性.
- Make sure you do not expose a
DbSet<HairCutStyle>
in yourDbContext
-derived class - Make sure you do not have any mention of
HairCutStyle
in yourOnModelCreating
override - Mark your
HairCutStyle
property using theNotMapped
attribute.
这篇关于实体框架代码优先:如何忽略类的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!