我想将一个Entity Framework层添加到具有现有数据库模式的现有应用程序中(无法更改此设置)。
我想用差异定义一个简单的一对多关系,外键和类型在表a和b中是不同的。
类/表A(事件)
[Table("Events")] public class Event { public Event() { Participants= new List<MemberCollection>(); } [Key] public int EventNumber { get; set; } public Guid? MemberCollectionId{ get; set; } [ForeignKey("CollectionId")] public virtual ICollection<MemberCollection> Participants{ get; set; } }类/表B(MemberCollection)
[Table("MemberCollections")] public class MemberCollection { [Key] public Guid CollectionId { get; set; } public int MemberNumber { get; set; } [StringLength(30)] public string RoleId { get; set; } }上面的代码导致以下异常。
引用约束的从属角色中的所有属性的类型必须与主体角色中的相应属性类型相同。 实体'MemberCollections'上的属性'CollectionId'的类型与引用约束'Event_MemberCollections'中实体'Event'上的属性'EventNumber'的类型不匹配。
如何告诉Entity Framework映射是通过MemberCollectionId完成的,而不是通过EventNumber完成的?
谢谢!
I want to add an Entity Framework layer to an existing application with an existing database schema (no way to change this).
I want to define a simple one-to-many relationship with the difference, that the foreign key and type is different in table a from b.
Class/Table A (Event)
[Table("Events")] public class Event { public Event() { Participants= new List<MemberCollection>(); } [Key] public int EventNumber { get; set; } public Guid? MemberCollectionId{ get; set; } [ForeignKey("CollectionId")] public virtual ICollection<MemberCollection> Participants{ get; set; } }Class/Table B (MemberCollection)
[Table("MemberCollections")] public class MemberCollection { [Key] public Guid CollectionId { get; set; } public int MemberNumber { get; set; } [StringLength(30)] public string RoleId { get; set; } }The code above leads to the following exception.
The types of all properties in the Dependent Role of a referential constraint must be the same as the corresponding property types in the Principal Role. The type of property 'CollectionId' on entity 'MemberCollections' does not match the type of property 'EventNumber' on entity 'Event' in the referential constraint 'Event_MemberCollections'.
How can I tell Entity Framework that the mapping is done through MemberCollectionId and not through EventNumber?
Thanks!
最满意答案
如果数据库已经存在,您是否有任何理由不使用数据库优先机制? 它将自动为您创建所有实体和关系。
所有类都创建为partials,因此您仍然可以扩展EF层中的类等。
我总是倾向于像这样创建我的表,因为我总是喜欢在EF之外设置我的数据库结构,因为我对SQL更有经验,我可以集中精力优化我的数据库。
If the database already exists, is there any reason you're not using the Database First Mechanism? It will automatically create all entities and relationships for you.
All your classes are created as partials so you can still extend the classes etc in your EF layer.
I always tend to create my tables like this as I've always preferred setting up my database structure outside of EF as I was more experienced with SQL and I can concentrate on optimizing my DB first.
更多推荐
发布评论