简体   繁体   English

实体框架-定义没有集合访问器的get

[英]Entity Framework - defining get without set accessors

I created a new class library project in Visual Studio 2012, to define data classes in order to enable new database creation using Entity Framework code first. 我在Visual Studio 2012中创建了一个新的类库项目,以定义数据类,以便首先使用Entity Framework代码创建新的数据库。 So I created 3 classes: 因此,我创建了3个类:

Product as next: 下一个产品:

namespace MyClassLibrary
{
    public class Product
    {
        public virtual int ID { get; set; }
        public virtual string Name { get; set; }
    }
}

Category as next: 下一个类别:

using System.Collections.Generic;

namespace MyClassLibrary
{
    public class Department
    {
        public virtual int ID { get; set; }
        public virtual string Name { get; set; }
        public virtual ICollection<Product> Products { get; set; }
    }
}

and ICategoryDataSource as next: 接下来是ICategoryDataSource:

using System.Linq;

namespace MyClassLibrary
{
    public class ICategoryDataSource
    {
        IQueryable<Product> Products { get; }
        IQueryable<Category> Categories { get; }
    }
}

In the last class, I get the next error message: 'MyClassLibrary.ICategoryDataSource.Products.get' must declare a body because it is not marked abstract or extern. 在上一类中,我收到下一条错误消息:'MyClassLibrary.ICategoryDataSource.Products.get'必须声明一个主体,因为它没有被标记为abstract或extern。 Automatically implemented properties must define both get and set accessors. 自动实现的属性必须定义get和set访问器。

I do not need a setter here, please advise how can I avoid using set accessors. 我在这里不需要设置器,请告知如何避免使用设置访问器。

By the name in the last code section, I assume you want ICategoryDataSource to be an interface, not a class: 通过最后一个代码部分中的名称,我假设您希望ICategoryDataSource成为接口,而不是类:

using System.Linq;

namespace MyClassLibrary
{
    public interface ICategoryDataSource
    {
        IQueryable<Product> Products { get; }
        IQueryable<Category> Categories { get; }
    }
}

You can't ever have an automatic property in a concrete class which only has an automatic getter or automatic setter. 在具体的类中,永远不可能只有自动属性,而只有一个自动获取器或自动设置器。 How would you get the data into that property in order to be able to pull it out? 您如何将数据放入该属性以便能够将其拉出?

You can however do that in abstract classes or interfaces, both of which effectively say "I don't care how data gets in here, I just require that it can be pulled out." 但是,您可以在抽象类或接口中做到这一点,它们都有效地表示“我不在乎数据如何进入这里,我只要求可以将其取出即可。”

Probably what you need is a private setter. 您可能需要的是私人二传手。

public IQueryable<Product> Products { get; private set; }

is perfectly valid, in any class. 在任何课程中都是完全有效的。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM