Solution 1 :
You could use SQLite-Net Extensions
to achieve this function, Add a Foreign key in the Product
class.
Here is running GIF about your project.First of all, I use “12” account to login in, here are several records in the product page. Then I restart your application, to create new account called “34”, when I log in, it have new shopping list, you can add product to the pages.
I changed Product
like following code.
public class Product
{
[PrimaryKey, AutoIncrement]
public int ID { get; set; }
public string Name { get; set; }
public string Notes { get; set; }
public bool Bought { get; set; }
[ForeignKey(typeof(User))]
public int UserId { get; set; }
[ManyToOne] // Many to one relationship with Stock
public User User { get; set; }
}
I changed User
like following code.
public class User
{
[PrimaryKey, AutoIncrement]
public int ID { get; set; }
public string Username { get; set; }
public string Password { get; set; }
public string Email { get; set; }
[OneToMany(CascadeOperations = CascadeOperation.All)]
public List<Product> Products { get; set; }
}
If you want to insert the data to Product
table. You should change Add event like following code.
saveButton.Clicked += async (sender, e) =>
{
var product = (Product)BindingContext;
await App.ProductDataBase.SaveItemAsync(product);
//check the data
var products = App.ProductDataBase.GetItemsAsync();
var usersFrst = UserDatabase.Database.GetWithChildren<User>(user.ID);
if (user.Products == null)
{
user.Products = new List<Product>() { product };
}
else
{
user.Products.Add(product);
}
//Update the changes into the database
UserDatabase.Database.UpdateWithChildren(user);
await Navigation.PopAsync();
};
When U login by new account, you should transfer User object. I update your demo, you can download it and test it.
https://github.com/851265601/Xamarin.Android_ListviewSelect/blob/master/shopper.zip
Problem :
I’m developing shopping list app with Xamarin and SQlite and I struggle with one problem. I have 2 tables – Users
and Products
. Registration and login work fine but the problem is how to serve a new empty shopping list. For now, it doesn’t matter on which user I’m logged in, it always shows the same list.
I don’t know exactly which part of code should I paste here so here is a repository: https://github.com/przezro098/Shopper.
Comments
Comment posted by How to Ask
please read
Comment posted by Saamer
You should connect the shopping list to the user. So, have the user’s unique id as one of the properties/columns in your table. Then you can filter out the shopping list by the user who is viewing the list.
Comment posted by Leon Lu – MSFT
Are there any update for this issue? If this answer is helpful, please accept it (click the ☑️ in the upper left corner of this answer ) it will help others who have similar issue.