简体   繁体   中英

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. So I created 3 classes:

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:

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. Automatically implemented properties must define both get and set accessors.

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:

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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