SQL表到实体的转换.Net EF 5代码优先
本文关键字:EF 代码 Net 转换 实体 SQL | 更新日期: 2023-09-27 18:05:39
我正在尝试转换旧的网站使用ASP。Net 4.5和EF5代码第一,但有一个表从旧网站我不知道如何转换,因为它有两个列,两者都引用同一列在它的父表。谁能帮我转换这张桌子?
CREATE TABLE dbo.tblCollectionsList
(
ListID smallint IDENTITY(0,1) NOT NULL,
SectionID smallint NOT NULL,
IncludedSectionID smallint NOT NULL,
CONSTRAINT PK_CollectionsList_ListID PRIMARY KEY CLUSTERED (ListID ASC),
CONSTRAINT FK_CollectionList_SectionInfo FOREIGN KEY (SectionID) REFERENCES dbo.tblSectionInfo (SectionID),
CONSTRAINT FK_CollectionList_SectionInfo2 FOREIGN KEY (IncludedSectionID) REFERENCES dbo.tblSectionInfo (SectionID)
)
请原谅表名的个人偏好,但您面临的问题是级联删除,您可以在模型创建中关闭此行为:
[Table("Section")]
public class Section
{
[Key]
public virtual int Id { get; set; }
public virtual string Description { get; set; }
}
[Table("List")]
public class List
{
[Key]
public virtual int Id { get; set; }
[Required]
[ForeignKey("Section")]
public virtual int SectionId { get; set; }
public virtual Section Section { get; set; }
[Required]
[ForeignKey("IncludedSection")]
public virtual int IncludedSectionId { get; set; }
public virtual Section IncludedSection { get; set; }
}
public class SectionContext : DbContext
{
protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
modelBuilder.Conventions.Remove<OneToManyCascadeDeleteConvention>();
base.OnModelCreating(modelBuilder);
}
public DbSet<Section> Sections { get; set; }
public DbSet<List> Lists { get; set; }
}
这是使用属性,你也可以做同样的事情没有属性,而不是使用OnModelCreating
中的FluentApi。
[Table("tblCollectionsList")]
public class CollectionsList
{
[Key]
public byte ListID {get;set;}
public byte SectionID {get;set;}
public byte IncludedSectionID {get;set;}
[ForeignKey("SectionID")]
public virtual Section Section {get;set;}
[ForeignKey("IncludedSectionID")]
public virtual Section IncludedSection {get;set;}
}