MVVMCross Community SqLite - Relationship between tables - sqlite

I have two simple tables as follow:
public class MediaPartner
{
[PrimaryKey, AutoIncrement]
public int Id { get; set; }
public string PhoneNumber { get; set; }
public string CompanyName { get; set; }
public double Lat { get; set; }
public double Lng { get; set; }
public DateTime InsertedUtc { get; set; }
}
public class ImageGroup
{
[PrimaryKey, AutoIncrement]
public int Id { get; set; }
public List<MediaPartner> IdMediaPartner { get; set; }
public string ImagePath { get; set; }
public bool IsSent { get; set; }
public DateTime InsertedUtc { get; set; }
}
The problem:
public List< MediaPartner > IdMediaPartner { get; set; }
OR
public MediaPartner IdMediaPartner { get; set; }
does not compile.
My question is: Is there a way to build one-to-many relationship between these two tables?
Thank you!

SQLite-net only provides cross-table referencing using indexing like:
public class Stock
{
[PrimaryKey, AutoIncrement]
public int Id { get; set; }
[MaxLength(8)]
public string Symbol { get; set; }
}
public class Valuation
{
[PrimaryKey, AutoIncrement]
public int Id { get; set; }
[Indexed]
public int StockId { get; set; }
public DateTime Time { get; set; }
public decimal Price { get; set; }
}
There is at least one extension to sqlite-net which allows OneToMany attributes to be declared - see https://bitbucket.org/twincoders/sqlite-net-extensions which enables code like:
public class Stock
{
[PrimaryKey, AutoIncrement]
public int Id { get; set; }
[MaxLength(8)]
public string Symbol { get; set; }
[OneToMany] // One to many relationship with Valuation
public List<Valuation> Valuations { get; set; }
}
public class Valuation
{
[PrimaryKey, AutoIncrement]
public int Id { get; set; }
[ForeignKey(typeof(Stock))] // Specify the foreign key
public int StockId { get; set; }
public DateTime Time { get; set; }
public decimal Price { get; set; }
[ManyToOne] // Many to one relationship with Stock
public Stock Stock { get; set; }
}
I'm not sure of the exact implementation of this - e.g. I don't know if this uses real FOREIGN KEY constraints - but the code is open source, is under active development, has mvvmcross plugin support built-in, is cross platform and is available for forking and for contributions.

Related

Need to create an API on the basis of ForeignKey in dotnet core

Here is my Schema and with two Foreign Key in an intermediate table. I am beginner in Core dotnet so unable to crate API to show the department in the school.
public class DepartmentSchool
{
public int Id { get; set; }
public int DepartmentID { get; set; }
[ForeignKey("DepartmentID")]
public virtual Department Department{ get; set; }
public int SchoolsId { get; set; }
[ForeignKey("SchoolsId")]
public virtual Schools Schools { get; set; }
Here I want to get all department related to school id, how can i get all the department though the School id in dotnetcore API.
Here is the school class entity schema.
public partial class Schools
{
public int ID { get; set; }
public string UicCode { get; set; }
public int SchoolSystemsId { get; set; }
public string BannerUrl { get; set; }
public string Name { get; set; }
public string Description { get; set; }
public string ImageUrl { get; set; }
public int UserID { get; set; }
public int? Status { get; set; }
public DateTime? CreatedAt { get; set; }
public int? CreatedBy { get; set; }
public DateTime UpdatedAt { get; set; }
public int? ModifiedBy { get; set; }
[ForeignKey("SchoolSystemsId")]
public PrivateSchoolSystem PrivateSchoolSystems { get; set; }
And more here is the department schema.
public partial class Department
{
public int Id { get; set; }
public string Title { get; set; }
public DateTime CreatedAt { get; set; }
public DateTime UpdatedAt { get; set; }
public int CreatedBy { get; set; }
public int UpdatedBy { get; set; }
public int SchoolSystemsID { get; set; }
[ForeignKey("SchoolSystemsID")]
public virtual PrivateSchoolSystem PrivateSchoolSystems { get; set; }
And I am trying to get a department list in the query in the following controller.
[Route("api/[controller]")]
[ApiController]
public class DepartmentSchoolController : ControllerBase
{
private readonly learning_gpsContext _learning_GpsContext;
public DepartmentSchoolController(learning_gpsContext learning_GpsContext)
{
_learning_GpsContext = learning_GpsContext;
}
[HttpGet("school/{schoolId}/departments")]
public IActionResult GetDepartmentsFromSchool(int schoolId)
{
var school = _learning_GpsContext.Schools.Where(e=>e.Id == schoolId).FirstOrDefault();
if (school == null)
return NotFound();
var departments = _learning_GpsContext.DepartmentSchool
.Where(e=>e.SchoolsId == schoolId).Select(e=>e.Department);
return Ok(departments);
}
For further learning check this tutorial. You should also understand what REST is and for basic questions always take a look at the official documenation.

Entity Framework many to many relation error

I'm trying to create a many-to-many relationship between my two tables, but when I run Update-Database command I get this error:
Introducing FOREIGN KEY constraint 'FK_dbo.ExamQuestions_dbo.Questions_Question_Id' on table 'ExamQuestions' may cause cycles or multiple cascade paths. Specify ON DELETE NO ACTION or ON UPDATE NO ACTION, or modify other FOREIGN KEY constraints.
Could not create constraint or index. See previous errors.
My first entity is :
public class Question
{
public Question()
{
this.Exams = new HashSet<Exam>();
}
[Key]
public int Id { get; set; }
[Required(ErrorMessage="Question is Required")]
[Display(Name="Question")]
[AllowHtml]
public string QuestionText { get; set; }
// public bool IsMultiSelect { get; set; }
public string Hint { get; set; }
public string HelpLink { get; set; }
public int Marks { get; set; }
public byte[] ImageData { get; set; }
[StringLength(50)]
public string MimeType { get; set; }
public byte[] Audio { get; set; }
public int QuestionTypeId { get; set; }
public int TopicId { get; set; }
public int DifficulityLevelId { get; set; }
public int SubjectId { get; set; }
public DifficultyLevel QuestionDifficulity { get; set; }
public Topic Topic { get; set; }
public virtual ICollection<Option> Options { get; set; }
public ICollection<Exam> Exams { get; set; }
}
And the second entity is:
public class Exam
{
public Exam()
{
this.Questions = new HashSet<Question>();
}
[Key]
public int Id { get; set; }
[Required]
public string Name { get; set; }
[Required]
public int Duration { get; set; }
[Required]
public int TotalQuestion { get; set; }
[Required]
public int TotalMarks { get; set; }
public bool SectionWiseTime { get; set; }
public bool QuestionWiseTime { get; set; }
public bool AllQustionRequired { get; set; }
public bool AllowBackForward { get; set; }
public bool SuffleSubjectWise { get; set; }
public bool SuffleOptionWise { get; set; }
public bool GroupSubjectWise { get; set; }
[Required]
public int ExamTypeId { get; set; }
[Required]
public int ExamInstructionId { get; set; }
[Required]
public int DifficultyLevelId { get; set; }
public virtual ExamType ExamType { get; set; }
public virtual ExamInstruction ExamInstruction { get; set; }
public virtual DifficultyLevel DifficultyLevel { get; set; }
public virtual ICollection<Question> Questions { get; set; }
//public virtual ICollection<ExamSchedule> ExamSchedules { get; set; }
}
Can someone tell me where I'm going wrong?
By default, EF has cascading deletes set. This error is warning you that this can cause cascading deletes with many to many relationships. And is probably not what you intend to have happen on a delete/update.
You can remove the OneToManyCascadeDeleteConvention in the OnModelCreating method, or on the fluent mapping for each entity.
Details are provided in this SO Answer

Mapping existing database with code first approch

I have implemented asp .net application without Code first approach. now i want to build different system with existing database and code first.
public class EmployeeEntity
{
public int Id { get; set; }
public string ResourceCode { get; set; }
public string FirstName { get; set; }
public string LastName { get; set; }
public DateTime DateOfBirth { get; set; }
public int Gender { get; set; }
public int Status { get; set; }
public string NIC { get; set; }
}
now i want to add code first entities.
[Table("ExternalApplicantEntity")]
public class ExternalApplicantEntity
{
[Key]
[DatabaseGenerated(DatabaseGeneratedOption.Identity)]
public int ApplicantID { get; set; }
//[ForeignKey("EmployeeEntity")]
//public int Created_By { get; set; }
//public virtual EmployeeEntity EmployeeEntity { get; set; }
public string NIC { get; set; }
public string Mobile { get; set; }
public string Institute { get; set; }
how i combine these codes?

Foreign Keys wont create in SQLite database using SQLite.net

I am trying to set up a SQLite database using SQLite.Net and SQLiteNetExtensions. I cant seem to get the foreign keys to create in the database. I have dropped all tables and used the model classes to recreate them again. I have checked the pragma in SQLite manager and foreign keys are turned on. In my example, a plot can have many trees. Any suggestions on what i might be missing?
public class Tree
{
[PrimaryKey, AutoIncrement]
public int TreeId { get; set; }
[NotNull]
public int TreeNumber { get; set; }
[NotNull]
public double Dbhob { get; set; }
public double? Height { get; set; }
[NotNull,Default(value: false)]
public bool? HeightTree { get; set; }
public string QualityCode { get; set; }
[ForeignKey(typeof(Plot))]
public int PlotId { get; set; }
[ManyToOne]
public Plot PlotInverse { get; set; }
}
public class Plot
{
[PrimaryKey, AutoIncrement]
public int PlotId { get; set; }
[NotNull, Unique]
public System.Guid PlotGuid { get; set; }
[NotNull, MaxLength(60)]
public string Strata { get; set; }
[NotNull, MaxLength(60)]
public string PlotNumber { get; set; }
public DateTime MeasureDate { get; set; }
[MaxLength(70)]
public String AssessorLead { get; set; }
[MaxLength(60)]
public String AssessorCrew { get; set; }
[Default(value: 0)]
public double PlotArea { get; set; }
public double BasalArea { get; set; }
[OneToMany("PlotId","PlotId")]
public List<Tree> Trees { get; set; }
}
Foreign keys attributes are not created in the sqlite database as sqlite-net doesn't have support for Foreign Keys and SQLite-Net Extensions is built on top of it. They are used in runtime to save and load related objects.
As a side note, you should change this line:
[OneToMany("PlotId","PlotId")]
public List<Tree> Trees { get; set; }
To this:
[OneToMany("PlotId","PlotInverse")]
public List<Tree> Trees { get; set; }
or remove it all together and let auto-discovery do its magic:
[OneToMany]
public List<Tree> Trees { get; set; }

Entity Framework WebApi Circular dependency serialization error

I think, I've read everything about this error and I tried everything. Here are my models:
Main:
public class Trip
{
public int TripId { get; set; }
public string Name { get; set; }
public string ShortDescription { get; set; }
public string Country { get; set; }
public float BasicPrice { get; set; }
public virtual ICollection<ApartmentType> ApartmentType { get; set; }
public virtual ICollection<TransportMethod> TransportMethod { get; set; }
public virtual ICollection<FeedingType> FeedingType { get; set; }
}
ApartmentType:
public class TransportMethod
{
public int TransportMethodId { get; set; }
public int TripId { get; set; }
public string Name { get; set; }
public float Price { get; set; }
}
FeedingType:
public class FeedingType
{
public int FeedingTypeId { get; set; }
public int TripId { get; set; }
public string Description { get; set; }
public float Price { get; set; }
}
TransportType:
public class TransportMethod
{
public int TransportMethodId { get; set; }
public int TripId { get; set; }
public string Name { get; set; }
public float Price { get; set; }
}
When serializng the Trip entity I get a circular dependency error. Things i tried:
Disable lazy loading in DbContext.
Adding
json.SerializerSettings.PreserveReferencesHandling=Newtonsoft.Json.PreserveReferencesHandling.All; to GLobal.asax
Adding a decorator [IgnoreDataMember] to TripId in every child entity.
Mapping this entity to a ViewModel which doesn't contain the ICollection members. - This worked ok, but at some point I will want to get those lists to the client.
I really don't know what's going on. What am I missing? I really can't spot any circular dependency.
Have you tried adding the [JsonIgnore] attribute to the TripId to the children entities?
http://james.newtonking.com/projects/json/help/html/T_Newtonsoft_Json_JsonIgnoreAttribute.htm
or setting
json.SerializerSettings.ReferenceLoopHandling = ReferenceLoopHandling.Ignore;

Resources