实体框架问题 [英] Entity Framework question

查看:69
本文介绍了实体框架问题的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

假设您有一个SQL Server数据库(TestDB),其中只包含两个可以通过执行以下Transact-SQL创建的表:



Suppose you have a SQL Server database (TestDB) containing only two tables that can be created by executing the following Transact-SQL:

CREATE TABLE Person(
   personId INT PRIMARY KEY IDENTITY(1,1),
   name VARCHAR(50)
)

CREATE TABLE House(
   personId INT,
   houseId INT,
   builtDate DATETIME,
   PRIMARY KEY(personId, houseId)
)





理想情况下,表中的字段 personId 将是一个外键,引用表 Person 中的字段 personId ,但是你可以看,它不是。此外,假设数据库模式 CAN NOT 被修改。



我想通过使用Entity Framework来使用以下类来表示这些表:





Ideally, the field personId in the table House would be a foreign key referencing the field personId in the table Person, but as you can see, it is not. Moreover, assume the database schema CANNOT be modified.

I would like to have the following classes to represent those tables by using Entity Framework:

[Table("Person")]
public class Person
{
   [Column("personId")]
   public int Id{ get; set; }
   
   [Column("name")]
   public string Name{ get; set; }

   public List<House> Houses{ get; set; }
}

[Table("House")]
public class House
{
   [Column("personId")]
   public int OwnerId { get; set; }
   
   [ForeignKey("OwnerId")] 
   public Person Owner { get; set; }
   
   [Column("houseId")]
   public int HouseId{ get; set; }
   
   [Column("builtDate")]
   public DateTime BuiltDate{ get; set; }
}

public class EFDbContext : DbContext
{
   public DbSet<Person> Persons {get; set;}

   public DbSet<House> Houses {get; set;}
}





我想这会是如果在 Person(personId) House(personId),但请记住数据库中没有外键约束。



我认为关键问题是: 如何当你真的没有外键时你会模拟外键吗?



请记住我无法触及数据库。



谢谢。



I think this would be the model of classes that Entity Framework would generate if there were a relationship in the database between Person(personId) and House(personId), but remember there is no foreign key constraint in the database.

I think the key question is: How would you simulate having a foreign key when you actually don''t have it?

Remember I cannot touch the database.

Thanks.

推荐答案

所以你需要按原样导入db模式(没有关系)那不存在)



如果sql没有这种关系我认为从sql表创建模型会按照你的预期行事,没有它。

但要注意小心管理身份证件





你试图输入sch吗? ema?

结果是什么?
so you need to import the db schema as is (without the relation that not exists )

if the sql do not have the relation i think that creating the model from the sql tables would act as you expect, without it.
BUT take care to manage the id(s) carefully


did you tried to import the schema ?
what was the result?


这篇关于实体框架问题的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆