微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

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

使用“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;组;}

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。

相关推荐