相关疑难解决方法(0)

实体框架中的主/外键

我在MVC 3应用程序中创建了一个实体类.名为RegistryId的属性之一是主键和外键.如何创建列主键和外键?我没有使用EF ORM设计师.我正在手工编写课程.

entity-framework-4 ef-code-first entity-framework-4.1

31
推荐指数
1
解决办法
2万
查看次数

继承和复合外键 - 基类中键的一部分,派生类中的另一部分

我在为以下示例数据库模式(在SQL Server中)创建实体框架代码优先映射时遇到问题:

具有复合外键的数据库模式

每个表都包含一个TenantId,它是所有(复合)主键和外键(多租户)的一部分.

A Company是a Customer或a Supplier,我尝试通过Table-Per-Type(TPT)继承映射对此进行建模:

public abstract class Company
{
    public int TenantId { get; set; }
    public int CompanyId { get; set; }

    public int AddressId { get; set; }
    public Address Address { get; set; }
}

public class Customer : Company
{
    public string CustomerName { get; set; }

    public int SalesPersonId { get; set; }
    public Person SalesPerson { get; set; }
}

public class Supplier : Company
{ …
Run Code Online (Sandbox Code Playgroud)

.net inheritance entity-framework table-per-type ef-code-first

17
推荐指数
1
解决办法
4191
查看次数

EntityFramework匿名复合键属性名称冲突

我正在使用EntityFramework 5(或.Net Framework 4.0的4.3)

在我的DbContext对象中,我已经设置了正确的DbSet,并且对象包含对彼此的正确引用.这对我来说并不新鲜,事情也很顺利.

现在在这种情况下,我有一些复合键,有时包括表的外键(在这种情况下是对象).为此,我使用HasKey<>()的功能OnModelCreating中的DbContext的方法.当这些属性具有不同的名称时,没有问题,但是当这些属性具有相同的名称时,无法进行迁移.

一个例子:

protected override void OnModelCreating(DbModelBuilder modelBuilder)
    {
        // ...

        modelBuilder.Entity<PatientVisit>().ToTable("PatientVisits");
        modelBuilder.Entity<PatientVisit>().HasKey(x => 
            new { x.Patient.Code, x.Code });

        // ...

        base.OnModelCreating(modelBuilder);
    }
Run Code Online (Sandbox Code Playgroud)

正如您在提供的代码中看到的那样,对象PatientVisit具有名为Code的属性,但只要与不同的患者重复该属性,就可以重复此属性.实体Patient还有一个名为Code的密钥.

匿名类型不能有两个推断同名的属性(显而易见).典型的解决方案是将匿名类型的属性命名为:

protected override void OnModelCreating(DbModelBuilder modelBuilder)
    {
        // ...

        modelBuilder.Entity<PatientVisit>().ToTable("PatientVisits");
        modelBuilder.Entity<PatientVisit>().HasKey(x => 
            new { PatientCode = x.Patient.Code, VisitCode = x.Code });

        // ...

        base.OnModelCreating(modelBuilder);
    }
Run Code Online (Sandbox Code Playgroud)

但是这样做,当我尝试添加迁移时,会抛出此错误消息.

The properties expression 'x => new <>f__AnonymousType3`2(PatientCode 
= x.Patient.Code, VisitCode = x.Code)' is not valid. The expression 
should represent a property: C#: …
Run Code Online (Sandbox Code Playgroud)

c# anonymous-types ef-code-first ef-migrations entity-framework-4.3

7
推荐指数
1
解决办法
2475
查看次数