问题
I have created a database, linked it with DomainService's within my Silverlight Application. Now I want to be able to perform certain actions, such as Registration, Login etc. by using the service.
How would I be able to do this. I have preset methods created in the service, e.g. InsertUser but it only requires one parameter, so I'm not sure how it works. In the metadata I have all fields etc.
Can anyone help me out here.
Thanks.
public IQueryable<User> GetUsers()
{
return this.ObjectContext.Users;
}
public void InsertUser(User user)
{
if ((user.EntityState != EntityState.Detached))
{
this.ObjectContext.ObjectStateManager.ChangeObjectState(user, EntityState.Added);
}
else
{
this.ObjectContext.Users.AddObject(user);
}
}
For retrieving User I have used (as a base from TBohnen.jnr code):
UserContext _userContext = new UserContext();
public MainPage()
{
InitializeComponent();
LoadOperation loGetUsers = _userContext.Load(_userContext.GetUsersQuery());
loGetUsers.Completed += new EventHandler(loGetUsers_Completed);
}
void loGetUsers_Completed(object sender, EventArgs e)
{
LoadOperation<Web.User> lo = (LoadOperation<Web.User>)sender;
var user = _userContext.Users;
MessageBox.Show(user.ToString());
}
回答1:
This is to add a new user:
YourDomainContext dc = new YourDomainContext();
User userToAdd = new User();
//You will have to set your properties here as I don't know them, I will give an example.
userToAdd.username = "NewUser";
dc.User.Add(userToAdd);
dc.SubmitChanges();
To retrieve your existing users:
YourDomainContext dc = new YourDomainContext();
LoadOperation loGetUsers = dc.Load(dc.GetUsersQuery());
loGetUsers.Completed += new EventHandler( loadOperation_Completed );// You will see there is a callback overloads as well
and then add this as well.
private void loadOperation_Completed( object sender, EventArgs e )
{
LoadOperation<User> lo = (LoadOperation<User>)sender;
//Have a look at all the properties like lo.Error etc. but to see the retrieved users you can either use:
var users = lo.AllEntities;
//or if you declared your domaincontext as a class level parameter:
var users = dc.User;
foreach (Web.User user in users)
{
MessageBox.show(user.username);
}
}
This will trigger an async call that get's all the users and will add it to the DomainContext and you will be able to access it through dc.User
来源:https://stackoverflow.com/questions/5694290/perform-sql-query-wcf-ria-silverlight