Access to classes
I am not sure where/how to search for this question so I thought asking the comminuty of stackoverflow is the best bet.
Basically I am designing a Project which will simply provide a logic project access to a LINQ to SQL model to perform C开发者_JAVA百科RUD on a database. So within the Data project I have the LINQ to SQL model class and a C# class to provide access to the Model as shown below
public class Connection : IDisposable
{
private DataModelDataContext _model;
public DataModelDataContext model
{
get { return _model; }
set { throw new Exception("Object \"model\" is not allowed to be created outside of its container class", new NotSupportedException()); }
}
public Connection(string username, string password)
{
User u = _model.Users.Where(u => u.Username == username && u.password == u.Password);
if (u == null)
throw new ApplicationException("User credentials are invalid", new AuthenticationException());
_model = new DataModelDataContext();
}
public void refreshAndKeepChanges(object entity)
{
_model.Refresh(RefreshMode.OverwriteCurrentValues, entity);
}
public int getChangesCount()
{
return _model.GetChangeSet().Deletes.Count() + _model.GetChangeSet().Inserts.Count() + _model.GetChangeSet().Updates.Count();
}
public void Dispose()
{
_model.SubmitChanges();
_model.Dispose();
}
}
What I want is, when I compile the DLL is for the Logic project to have access to the Connection class (above) but not the DataModelDataContext (as this would defeat the object of passing user credentials).
My question is how can expose the Connection class (as public which I have already done) but hide LINQ to SQL data model from the DLL but allow the Connection class access to it???
using an extra namespace for the LINQ to SQL model does not work, i have found adding the DLL allows access to all the namespaces within the project.
Just change the model
property to be internal, along with the DataModelDataContext
class (which is probably done by editing the DBML, either in the designer or by hand). It's fine for the Connection
class to know about internal classes - it just can't expose them publicly.
As a couple of asides:
- If the
model
setter is never going to be functional, why have it at all? Just get rid of it. - You should start following the .NET naming conventions
You change public DataModelDataContext model
to either
internal DataModelDataContext model
if you want it to be "public within that assembly, but private to all other assemblies"
protected DataModelDataContext model
or
private DataModelDataContext model
if you don't want to expose DataModelDataContext
to other classes in that assembly.
Most likely you want it as internal
.
The term you can search for (or read more directly on MSDN) is Access Modifiers.
精彩评论