我正在尝试使用以下模型创建mvc应用程序:(代码很大。我认为这对你来说更容易理解)
public class Job
{
public int JobId { get; set; }
public string Name { get; set; }
public List<Job> GetJobs()
{
List<Job> jobsList = new List<Job>();
jobsList.Add(new Job { JobId = 1, Name = "Operator" });
jobsList.Add(new Job { JobId = 2, Name = "Performer" });
jobsList.Add(new Job { JobId = 3, Name = "Head" });
return jobsList;
}
}
public class Person
{
public virtual int PersonId { get; set; }
public string FullName { get; set; }
public int JobId { get; set; }
public virtual Job Job;
public string Phone { get; set; }
public string Address { get; set; }
public string Passport { get; set; }
[DataType(DataType.MultilineText)]
public string Comments { get; set; }
}
public class PersonPaidTo : Person
{
[Key]
public override int PersonId { get; set; }
public virtual List<Order> Orders { get; set; }
}
public class Head : Person
{
[Key]
public override int PersonId { get; set; }
public Job Job { get; set; }
public Head()
{
Job.Id = 3;
}
}
我在字段Person
中的课程Job
中出错:
修饰符'virtual'对此项无效
答案 0 :(得分:32)
是的,此代码无效:
public virtual Job Job;
这是宣告字段,字段不能是虚拟的。你要么想要它成为一个财产:
public virtual Job Job { get; set; }
或只是一个字段:
// Ick, public field!
public Job Job;
(我的猜测是你想要前者,但两者都是有效的C#。)
答案 1 :(得分:0)
将字段设为私有并使用公共属性公开的正确方法。
//Field
private Job job;
//Property
public virtual Job Job
{
get { return job; }
set { job= value; }
}