加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 编程开发 > asp.Net > 正文

asp.net – 在使用“EF-Code First”时如何定义Keys?

发布时间:2020-12-16 03:37:00 所属栏目:asp.Net 来源:网络整理
导读:使用“EF-Code First”时,我得到一个ModelValidationException(在底部).它希望我定义一个Key,但我不确定它究竟意味着什么…… public class Unit{ Guid id; String public_id; String name; bool deleted;}public class MyDataContext : DbContext{ public D
使用“EF-Code First”时,我得到一个ModelValidationException(在底部).它希望我定义一个Key,但我不确定它究竟意味着什么……

public class Unit
{
    Guid id;
    String public_id;
    String name;        
    bool deleted;
}

public class MyDataContext : DbContext
{
    public DbSet<Unit> Units { get; set; }

    protected override void OnModelCreating(ModelBuilder modelBuilder)
    {
        modelBuilder.Entity<Unit>().ToTable("sometable");
    }
}

[TestFixture]
public class DataTests
{
    [Test]
    public void Test()
    {
        MyDataContext database = new MyDataContext();
        var o = database.Units;


        Console.WriteLine(o.Count()); // This line throws!
        Assert.IsTrue(true);
    }
}

System.Data.Entity.ModelConfiguration.ModelValidationException : One or more validation errors were detected during model generation:

System.Data.Edm.EdmEntityType: : EntityType ‘Unit’ has no key defined. Define the key for this EntityType.

System.Data.Edm.EdmEntitySet: EntityType: The EntitySet Units is based on type Unit that has no keys defined.

解决方法

对于希望EF为其创建数据库字段的所有字段,您需要使用属性,而不是私有局部变量.

Public Guid Id {get;组;}

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读