13

我正在尝试使用以下模型创建 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

修饰符“虚拟”对此项目无效

4

2 回答 2

36

是的,此代码无效:

public virtual Job Job;

那是声明一个field,并且 fields 不能是虚拟的。您要么希望它成为一个属性:

public virtual Job Job { get; set; }

或者只是一个字段:

// Ick, public field!
public Job Job;

(我的猜测是你想要前者,但两者都是有效的 C#。)

于 2012-10-15T16:09:52.833 回答
1

使字段私有并使用公共属性公开它的正确方法。

//Field
private Job job;

//Property
public virtual Job Job
    {
        get { return job; }
        set { job= value; }
    }
于 2016-03-02T11:11:30.127 回答