实体框架代码首先设置私有setter的值

时间:2017-04-19 19:21:47

标签: c# entity-framework

我有一个模型类:

public Account()
{

}

public Account(Guid id, int accountnumber, string accountType)
{
    Id = id;
    Accountnumber = accountnumber;
    AccountType = accountType;          
}

public Guid Id { get; private set; }
public int Accountnumber { get; private set; }
public string AccountType { get; private set; }

}

和DbContext类:

class BankContext : DbContext
{
    public DbSet<Account> Accounts { get; set; }
}

和我正在尝试的主要类添加值。

Account account = new Account();

BankContext bank = new BankContext();
bank.Accounts.Add(new Account(Guid.NewGuid(), 343, "Checkings")
{                 
    Id=Guid.NewGuid();// returns error."Id is not accessible"
});

在我决定从stackoverflow请求帮助之前,我做了很好的研究。如果有人可以指导我如何在这种情况下为私有元素添加值,我将非常感激。

1 个答案:

答案 0 :(得分:1)

在您的班级公开terminal-output。其中Id是私人套装。 所以你不能公开设置Id值。意味着你不能

Guid Id { get; private set; }

始终返回“Id is not accessible”错误。

另一个想法为什么你需要设置它。您已经使用构造函数设置了它。

 new Account(...)
{
    Id=Guid.NewGuid();
}

这很好玩。

相关问题