I am making a application in Xamarin forms but whatever I try I can't get the sqlite database working. I want to select all Categories where menu_ID = 1 how can I do this? I need this code inside a other page (CategoriePage.xaml.cs) can somewann help me with this?
Here is some code that I use:
(Tables.cs):
namespace AmsterdamTheMapV3
{
public class Categories
{
[PrimaryKey, AutoIncrement]
public int ID { get; set; }
public int Menu_ID { get; set; }
public string Name { get; set; }
public Categories()
{
}
}
public class Places
{
[PrimaryKey, AutoIncrement]
public int ID { get; set; }
public int Categorie_ID { get; set; }
public string Name { get; set; }
public Boolean Featured { get; set; }
public string OpenHours { get; set; }
public string Info { get; set; }
public string Images { get; set; }
public string Phone { get; set; }
public string Website { get; set; }
public string Adress { get; set; }
public Places()
{
}
}
public class Events
{
[PrimaryKey, AutoIncrement]
public int ID { get; set; }
public Events()
{
}
}
}
DB helper (TheMapDB.cs):
public class TheMapDB
{
private SQLiteConnection db;
public TheMapDB()
{
//Getting conection and Creating table
db = DependencyService.Get<ISQLite>().GetConnection();
db.CreateTable<Categories>();
db.CreateTable<Places>();
db.CreateTable<Events>();
var categories = new Categories()
{
ID = 1,
Menu_ID = 1,
Name = "test"
};
db.Insert(categories); // Insert the object in the database
}
public IEnumerable<Categories> GetCategories()
{
return (from t in db.Table<Categories>() select t).ToList();
}
//Get specific Categorie
public Categories GetCategorie(int id)
{
return db.Table<Categories>().FirstOrDefault(t => t.ID == id);
}
//Delete specific Categorie
public void DeleteCategorie(int id)
{
db.Delete<Categories>(id);
}
//Add new student to Categorie
public void AddCategorie(Categories categorie)
{
db.Insert(categorie);
}
}
}
CategoriePage.xaml.cs:
public partial class CategoriePage : ContentPage
{
static TheMapDB database;
TheMapDB categorie = new TheMapDB();
public CategoriePage(String txt)
{
InitializeComponent();
var layout = new StackLayout { Padding = new Thickness(5, 10) };
this.Content = layout;
if(txt.Equals("1"))
{
txt = "this text is number 1";
//needed code can't find soluction
}
var label = new Label { Text = txt, TextColor = Color.FromHex("#77d065"), FontSize = 20 };
layout.Children.Add(label);
}
}
thank you in advance,
I suggest you make a DAO class with a function like this: (or put this function in TheMapDB.cs)
public List<Category> GetCategoryByID(int menuID)
{
return db.Table<Category>().Where(x => x.menu_ID == menuID).ToList();
}
Then you can call this function in your DAO from everywhere you want. That seems the best solution to me.
When you put this function in the class TheMapDB.cs you can say in your CategoryPage.xaml.cs:
database.GetCategoryByID(menuID);
Related
I have successfully inserted data into two tables which are working fine. Now I am just stuck as to how I can get the details from both tables and update them. After inserting, I want to query both tables using an id and get the records, and then use the Id to update.
This is what I am looking for.
get data from two tables
update tables(pass id)
It must be an API that communicates with my classes because I want to display the data from the view
DB Models
1.
public class WholesaleRateSheetMarkup
{
[Key]
public int RateSheetMarkupId { get; set; }
[Required]
public int ResellerId { get; set; }
[StringLength(50)]
public string RatesheetName { get; set; }
}
2.
public class WholesaleRateSheet
{
[Key]
public int RateSheetId { get; set; }
[Required]
public int RateSheetMarkupId { get; set; }
public string CountryCode { get; set; }
public string Description { get; set; }
public decimal Peak { get; set; }
public bool IsSouthAfricanRate { get; set; }
public bool IsInertnationRate { get; set; }
public bool IsSpecificRate { get; set; }
public int DestinationGroupSetId { get; set; }
public int DestinationGroupId { get; set; }
public string DestinationLookup { get; set; }
public DateTime CreatedDate { get; set; }
public string CreatedByUsername { get; set; }
public DateTime LastUpdatedDate { get; set; }
public string UpdatedByUsername { get; set; }
}
My controller: This controller calls service class
[HttpPost]
[Route("[controller]/addRateSheet/{resellerId}/{productName}")]
public IActionResult AddRateSheet(int resellerId, string productName , int destinationGroupSetId, [FromBody]List<RateSheetSummary> rateSheetSummaries)
{
RateSheetService rateSheetService = new RateSheetService();
return Ok(rateSheetService.SaveRateSheet(resellerId, productName, rateSheetSummaries));
}
This is how I am saving to the database
public RateSheetModel SaveRateSheet(int resellerId, string productName, [FromBody]List<RateSheetSummary> rateSheetSummaries)
{
int latestId;
RateSheetModel rateSheetModel = new RateSheetModel();
try
{
#region Save rate sheet to the tabase
if (RateSheetObj != null)
{
#region WholesaleRateSheetMarkup
var wholesaleRateSheetMarkup = new WholesaleRateSheetMarkup
{
ResellerId = resellerId,
RatesheetName = productName,
};
_Context.WholesaleRateSheetMarkup.Add(wholesaleRateSheetMarkup);
_Context.SaveChanges();
//get latest RateSheetMarkupId
latestId = wholesaleRateSheetMarkup.RateSheetMarkupId;
#endregion
#region WholesaleRateSheet
#region commented out
List<WholesaleRateSheet> wholesaleRateSheets = new List<WholesaleRateSheet>();
foreach (var item in rateSheetSummaries)
{
wholesaleRateSheets.Add(new WholesaleRateSheet()
{
RateSheetMarkupId = latestId,
CountryCode = item.CountryCode,
Description = item.Description,
Peak = item.Peak,
IsSouthAfricanRate = item.IsSouthAfricanRate,
IsSpecificRate = item.IsSpecificRate,
DestinationGroupSetId = 1,
DestinationGroupId = 1,
DestinationLookup = item.DestinationLookup,
CreatedDate = DateTime.Now
}); ;
_Context.WholesaleRateSheet.AddRange(wholesaleRateSheets);
_Context.SaveChanges();
}
#endregion
}
}
}
}
Trying to fetch data from my tables. At this point, I don't know how to continue further as I want to get the details and so that I can bind the data from the view.
public RateSheetModel getRatesheetDetails(int rateSheetMarkupId)
{
RateSheetModel model = new RateSheetModel();
using (var context = new AppClientZoneContext())
{
var select = (from rsm in context.WholesaleRateSheetMarkup
join rs in context.WholesaleRateSheet
on rsm.RateSheetMarkupId equals rs.RateSheetMarkupId
where rsm.RateSheetMarkupId == rateSheetMarkupId
select new
{
rsm.RatesheetName,
rs.CountryCode,
rs.Description,
rs.Peak,
rs.IsSouthAfricanRate,
rs.IsInertnationRate,
rs.RateSheetMarkupId,
rs.IsSpecificRate,
rs.DestinationGroupSetId,
rs.DestinationGroupId,
rs.DestinationLookup,
rs.CreatedDate,
rs.CreatedByUsername,
rs.LastUpdatedDate,
rs.UpdatedByUsername,
}).FirstOrDefault();
}
return model;
}
Update API
[HttpPost]
[Route("[controller]/updateRateSheet/{resellerId}/{ratesheetId}")]
public IActionResult UpdateRateSheet(int resellerId, int ratesheetId, string productName)
{
RateSheetService UpdateRateSheetService = new RateSheetService();
return Ok(UpdateRateSheetService.UpdateRateSheet(resellerId,ratesheetId, productName));
}
Update function: I don't know how to best approach update functionality
public RateSheetModel UpdateRateSheet(int resellerId, int rateSheetId, string productName)
{
RateSheetModel mm = new RateSheetModel();
return mm;
}
Here I have two list var userListFromFriendTable = mainService.GetUserFromFriend(ChattingUserName); and var getAllUserFromMessageUserTable = mainService.GetalluserfromMessageUser(); whose implementation are
given below.
Now what is want is to remove all the Friend table FriendRequestReceiverName column data of userListFromFriendTable list from MessageUser table MessageUserName column of getAllUserFromMessageUserTable list.
Any help will be grate
public List<Friend> GetUserFromFriend(string chattingUserName)
{
var checkUser = uow.Repository<Friend>().FindBy(x => x.FriendRequestSenderName.ToLower() == chattingUserName.ToLower()).ToList();
return checkUser;
}
public List<MessageUser> GetalluserfromMessageUser()
{
var checkUser = uow.Repository<MessageUser>().GetAll().ToList();
return checkUser;
}
public class Friend
{
public int FriendId { get; set; }
public string FriendRequestSenderName { get; set; }
public string FriendRequestReceiverName { get; set; }
public int IsConfirmed { get; set; }
}
public class MessageUser
{
public int Id { get; set; }
public string MessageUserName { get; set; }
public int IsFriend { get; set; }
}
try this:
var names=userListFromFriendTable.Select(i=> i.FriendRequestReceiverName)
.OfType<string>()
.ToArray();
getAllUserFromMessageUserTable.RemoveAll(r => names.Contains( r.MessageUserName );
I am going to create an app in Xamarin forms and starting with SQLite. I need to have unique list items for each Main item in the app.
For example, I am having a list with items. When I am selecting an item in the list a new page will pop up and display the items of that item.
So from my point of view I am in need of two SQLite tables with relations between.
This is the Main table with all profiles
[Table("Profiles")]
public class ProfileItems
{
[PrimaryKey, AutoIncrement]
public int Id { get; set; }
public string ProfileName { get; set; }
public string ProfileRace { get; set; }
public string iconn = "icon.png";
public string ProfileIcon { get; set; }
public DateTime BDay { get; set; }
[OneToMany(CascadeOperations = CascadeOperation.All)]
public List<LoggItems> Loggs { get; set; }
}
This is the logg table for each Profile, which should be unique for each profile
[Table("Loggs")]
public class LoggItems
{
[PrimaryKey, AutoIncrement]
public int Id { get; set; }
public string Title { get; set; }
public string Text { get; set; }
[ForeignKey(typeof(ProfileItems))]
public int ProfileId { get; set; }
}
Adding the items like this
public class ProfileDatabase
{
readonly SQLiteAsyncConnection database;
public ProfileDatabase(string dbPath)
{
database = new SQLiteAsyncConnection(dbPath);
database.CreateTableAsync<ProfileItems>().Wait();
database.CreateTableAsync<LoggItems>().Wait();
}
//Profile
public Task<List<ProfileItems>> GetProfileAsync()
{
return database.Table<ProfileItems>().ToListAsync();
}
public Task<ProfileItems> GetProfileAsync(int id)
{
return database.Table<ProfileItems>().Where(i => i.Id == id).FirstOrDefaultAsync();
}
public Task<int> SaveProfileAsync(ProfileItems profileItems)
{
if (profileItems.Id != 0)
{
return database.UpdateAsync(profileItems);
}
else
{
return database.InsertAsync(profileItems);
}
}
public Task<int> DeleteProfileAsync(ProfileItems profileItems)
{
return database.DeleteAsync(profileItems);
}
//Logg
public Task<List<LoggItems>> GetLoggAsync()
{
return database.Table<LoggItems>().ToListAsync();
}
public Task<LoggItems> GetLoggAsync(int id)
{
return database.Table<LoggItems>().Where(i => i.Id == id).FirstOrDefaultAsync();
}
public Task<int> SaveLoggAsync(LoggItems loggItems)
{
if (loggItems.Id != 0)
{
return database.UpdateAsync(loggItems);
}
else
{
return database.InsertAsync(loggItems);
}
}
public Task<int> DeleteLoggAsync(LoggItems loggItems)
{
return database.DeleteAsync(loggItems);
}
}
Both Logg and Profile list/tables do work but they do not have any relations between so the loggs show the same in all profile.
How should I do this?
How about to use Linq and join the relationships.
1.- First you have to add the namespace:
using System.Linq;
2.- Change the property in the class ProfileItems to be a IEnumerable
[OneToMany(CascadeOperations = CascadeOperation.All)]
public virtual IEnumerable<LoggItems> Loggs { get; set; }
3.- This is the method to join the loggs with the profile items.
var profiles = await GetProfileAsync();
var loggs = await GetLoggAsync();
var query = from p in profiles
join l in loggs on p.Id equals l.ProfileId into list
select new ProfileItems
{
Id = p.Id,
ProfileIcon = p.ProfileIcon,
ProfileName = p.ProfileName,
ProfileRace = p.ProfileRace,
BDay = p.BDay,
Loggs = list
};
I think you must add "virtual" keyword for enabling lazy loading.
[OneToMany(CascadeOperations = CascadeOperation.All)]
public virtual List<LoggItems> Loggs { get; set; }
And there's the "[InverseProperty]" to specify their related navigation property.
public class LoggItems
{
*
[ForeignKey(typeof(ProfileItems))]
[InverseProperty("Loggs")]
public int ProfileId { get; set; }
*
}
I have a 3 level entity and I am having some trouble saving it.
public partial class Event
{
public Event()
{
Recurrences = new HashSet<Recurrence>();
}
public int Id { get; set; }
public string Title { get; set; }
public ICollection<Recurrence> Recurrences { get; set; }
}
public partial class Recurrence
{
public Recurrence()
{
AspNetUsers = new HashSet<AspNetUser>();
}
public int Id { get; set; }
public int EventId { get; set; }
public string Venue { get; set; }
public ICollection<AspNetUser> AspNetUsers { get; set; }
}
public partial class AspNetUser
{
public AspNetUser()
{
Recurrences = new HashSet<Recurrence>();
}
public string Id { get; set; }
public string UserName { get; set; }
public ICollection<Recurrence> Recurrences { get; set; }
}
The Post controller for the Event Class looks like this:
// POST: api/Events
[ResponseType(typeof(Event))]
public async Task<IHttpActionResult> PostEvent(EventDTO #event)
{
if (!ModelState.IsValid)
{
return BadRequest(ModelState);
}
var newEvent = new Event();
newEvent.Title = #event.Title;
newEvent.EventTypeId = #event.EventTypeId;
var recurrence = new Recurrence();
recurrence.Venue = #event.Venue;
var users = db.AspNetUsers.Where(u => #event.UserId.Contains(u.Id));
foreach (var u in users)
recurrence.AspNetUsers.Add(u);
newEvent.Recurrences.Add(recurrence);
db.Events.Add(newEvent);
await db.SaveChangesAsync();
return CreatedAtRoute("DefaultApi", new { id = newEvent.Id }, newEvent);
}
When I call the PostEvent method with an Event like DTO i get the http error code 500.
first, how can i add exception handling to capture the specific error and secondly, what I'm I doing wrong here?
Any help is deeply appreciated.
Thanks.
Hi I am new to entity framework. I have following objects
public partial class lr
{
public lr()
{
this.lr_history = new HashSet<lr_history>();
this.people = new HashSet<person>();
}
public int _id { get; set; }
public string name { get; set; }
public string notes { get; set; }
public virtual ICollection<lr_history> lr_history { get; set; }
public virtual ICollection<person> people { get; set; }
In my Web Api controller I have following code
public class lrController : ApiController
{
private CTM db = new CTM();
// GET api/addL
public IEnumerable<lr> Getlr()
{
from a in DbContext.Activities
return db.lr.AsEnumerable();
}
In above Get method it returns lr but i want to return my own object like
lr.id
lr.name
lr_history.description
lrh_history.rate
Can anyone show me how to achieve this? Than
Create a new model:
class HistoryModel
{
public int Id { get; set; }
public string Name { get; set; }
public string HistoryDescription { get; set; }
public string HistoryRate { get; set; }
}
and return that:
public IEnumerable<HistoryModel> Getlr()
{
from a in DbContext.Activities
return db.lr.AsEnumerable()
.Select(x => new HistoryModel
{
Id = x.id,
Name = x.name,
HistoryDescription = x.history.description,
HistoryRate = x.history.rate
});
}
Instade of return db.lr.AsEnumerable();
try this
return db.lr.ToList();