相关疑难解决方法(0)

EF代码优先 - 1对1可选关系

我想使用EF Code First在现有数据库中映射可选的1对1关系.

简单架构:

User
 Username
 ContactID

Contact
 ID
 Name
Run Code Online (Sandbox Code Playgroud)

显然ContactID加入了Contact.ID.ContactID字段可以为空,因此关系是可选的 - 0或1,从不多.

那么如何使用现有模式在EF Code First中指定此关系?

这是我到目前为止所尝试的:

public class User
{
    [Key]
    public string Username { get; set; }
    public int? ContactID { get; set; }

    [ForeignKey("ContactID")]
    public virtual Contact Contact { get; set; }
}

public class Contact
{
    [Key]
    public int ID { get; set; }
    public string Name { get; set; }

    public virtual User User { get; set; }
}

modelBuilder.Entity<User>().HasOptional<Contact>(u=> u.Contact)
    .WithOptionalDependent(c => c.User);
Run Code Online (Sandbox Code Playgroud)

我得到以下例外: …

one-to-one ef-code-first

26
推荐指数
1
解决办法
3万
查看次数

实体框架 - 外键 - 数据注释

我在EF中使用Data annotation,我有类:

[Table("Accounts")]
public class DbAccount
{
    public int Id { get; set; }
    public string Username { get; set; }

    public virtual DbLicense License { get; set; }
}

[Table("Licenses")]
public class DbLicense
{
    public int Id { get; set; }
    public int AccountId { get; set; }

    [ForeignKey("AccountId")]
    public virtual DbAccount Account { get; set; }
}
Run Code Online (Sandbox Code Playgroud)

我必须如何装饰属性public virtual DbLicense License {get; 组; }

EF投掷

无法确定类型'DbLicense'和'DbAccount'之间关联的主要结束.必须使用关系流畅API或数据注释显式配置此关联的主要结尾.

这项工作很好:

modelBuilder.Entity<DbAccount>()
            .HasRequired(x => x.License)
            .WithRequiredPrincipal();
Run Code Online (Sandbox Code Playgroud)

但是如何用注释来编写呢?

entity-framework

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