Question

I have alluded to this issue in my other question, but i think it's worthwhile breaking it out into its own question, as it's not really dependant on the other scenarios i mentioned.

Anyways - onto the Q, don't know if this is possible. Looking for a solution/workaround.

I have a Class Library, with nothing but POCO's:

MyCompany.MyProject.Domain.POCO

This assembly has a POCO like this:

public class Post
{
   public int PostId { get; set; }
   public int Name { get; set; }
      ...
}

Now, i have another Class Library, which is my DAL/Repository, and uses Entity Framework 4.0 for the persistence:

MyCompany.MyProject.Repositories

This assembly has a reference to the POCO project, as it needs to be perform CRUD operations on the POCO's (grab DB objects, project into POCO's, return, as well as modify POCO's).

Now, i also have a Web Application, which has a reference to both the POCO and Repository assembly.

If i do this:

somePOCO.PostId = 10;

I get a SQLException, as PostId is an IDENTITY field in the database, and hence should not be explicity set.

Is there a way i can hide the setter for these special properties, so that only the repository has access to the setter?

I can't think of a way to do it with regular accessibility modifiers (as none of them suit the scenario), can you guys think of a workaround?

Was it helpful?

Solution

you could make the setter internal, and make the internals visible to the repository assembly

[assembly: InternalsVisibleTo("MyLibrary.Repositories")]
public class Post
{
   public int PostId { get; internal set; }
   public int Name { get; internal set; }
      ...
}

This means that everything can 'get' those properties, but only this assembly, and the assembly containing the repository, can 'set'

OTHER TIPS

Mark all your setters as internal, then add the InternalsVisibleTo Attribute to your POCOs assembly:

 [assembly: InternalsVisibleTo( "MyCompany.MyProject.Repositories" )]  

Luke Schafer's is a good answer. It satisfies the technical requirement of the question. But I'd advise caution simply because this may not address the problem in the future.

Not to suggest over engineering but perhaps you might want to think about abstracting away further what you are doing with these objects that have the settable ID property. It may suffice to create this 'visibility' with this attribute decoration but i think it's sort of a hack for the problem. It might be cleaner to encapsulate the interaction between these objects with something else, thus removing the setter access from consuming code.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top