EF relation in constructor - asp.net

I get error;
Cannot implicitly convert type Sale in ICollection
when I do this, I have seen it in some examples and it is possible to do so.
Sale sale= new Sale(){ Id = 1 };
Service service = new Service() { Name= "SomeService",Sales=sale}; //I can't assign sale
public class Service: EntityBase
{
//public Service()
//{
// Sales= new HashSet<Sale>();
//}
public string Name{ get; set; }
public virtual ICollection<Sale> Sales{ get; set; }
}
How can i solve it?
I don't want to do: service.Sales.add(fact), if there is another way

If you were very opposed to using .Add and wanted to pass one or more Sale instances to the Service instance and have them added to the Sales collection then you could add a second constructor that takes one or more Sale instances like so.
public class Service: EntityBase
{
public Service() // empty constructor needed for EF
{}
public Service(params Sale[] sales)
{
Sales = new List<Sale>(sales);
}
public string Name{ get; set; }
public virtual ICollection<Sale> Sales{ get; set; }
}
// example with 2 sales
Sale sale1 = new Sale(){ Id = 1 };
Sale sale2 = new Sale(){ Id = 2 };
Service service = new Service(sale1,sale2) { Name= "SomeService" };
Leave the empty constructor in place as it is used by EF.

What you're saying here is that a Sale = List();
make a list of sales, add a sale to it, and then in the constructor say that Sales = the list of sales u made.
Sale sale = new Sale(){ Id = 1 };
List<Sale> sales = new List<Sale>();
sales.Add(sale);
Service service = new Service() { Name = "Service", Sales = sales };

Related

dapper left join & mapping query

There is one-to-many relation between Brand and Campaign entities,
With given Id I need to select Campaign and related Brand entity along with it.
TO do so:
public async Task<Campaign> GetAsync(int id)
{
using var dbConnection = _context.CreateConnection();
string query = #"SELECT c.[Id], c.[BrandId], c.[StartDate],
c.[EndDate],b.[Id] FROM [dbo].[Campaign] c
left join [dbo].[Brand] b on c.[BrandId] = b.[Id]
WHERE c.[Id] = #Id";
var campaign = await dbConnection.QueryAsync<Campaign, Brand, Campaign>(query, (campaign, brand) =>
{
campaign.Brand = brand;
return campaign;
}, splitOn: "BrandId", param: new { Id = id });
return campaign.FirstOrDefault();
}
code above not throws exception but child brand entity is not correct.(its dummy record, and BrandId is 0 whereas its valu is 5 in database)
whats missing here?
entity def:
public class Campaign : SqlEntityBase
{
public int BrandId { get; set; }
public DateTime? StartDate { get; set; }
public DateTime? EndDate { get; set; }
public Brand Brand { get; set; }
}
public class Brand : SqlEntityBase
{
public string Name { get; set; }
public List<Campaign> Campaign { get; set; } = new List<Campaign>();
}
Your SQL query doesn't make sense. You're splitting on BrandId in dapper but you never select anything to do with the brand in the query. With your current code, dapper is parsing the SQL column Id into your Campaign POCO (which it cant do because there isn't a property called Id nor have you anything mapped to it in the campaign class).
And then it see's BrandId and then parses everything after that into the Brand POCO, but your remaining columns that you're selecting are the start and end dates for the campaign.
In summary: You need to include the Brand data into the SQL query. You're joining onto the table, but only selecting the campaign data.

Passing Values from Page to Another page in List

this is mine model
public class QMSRejection
{
public string Date { get; set; }
public string Grade { get; set; }
public string Resd { get; set; }
public string Remarks { get; set; }
}
this is mine firstpage.xaml.cs from where I am passing a data to another page !
List<QMSRejection> DataToSave = new List<QMSRejection>();
var rej = new QMSRejection();
rej.Date = DateTime.Now.ToShortDateString();
rej.Grade = GradeID;
rej.Resd = ResdId;
DataToSave.Add(rej);
await Navigation.PushAsync(new Rejection2ndForm(DataToSave));
now on the second page I am receiving it, data is coming everything working fine !
public partial class Page2 : ContentPage
{
List<QMSRejection> DataToSave = new List<QMSRejection>();
public Rejection2ndForm(List<QMSRejection> models)
{
InitializeComponent ();
DataToSave = models;
}
}
var rej = new QMSRejection();
rej.Remarks = ent3.Text.ToString();
DataToSave.add(rej);
I have a fields Remarks which I am trying to add to existing data coming from page 1.But these lines are creating another IEnumerable in the datatoSave List and remarks field not getting added to previous data ! What should I do in place of these lines to do ?
As I have to add remarks field through page2.xaml.cs !
this creates a new QMSRejection object and adds it to your list
var rej = new QMSRejection();
rej.Remarks = ent3.Text.ToString();
DataToSave.add(rej);
if you instead want to modify an existing QMSRejection object
// [0] means the first object in the list
DataToSave[0].Remarks = ent3.Text.ToString();

Elasticsearch id field is empty using Nest IndexMany with Bulk indexing

Somehow, my object's id field is not being stored, but all other fields are?
The code:
// Assuming a list of Products
var products = // entity framework code to get a list of products
var node = new Uri("http://localhost:9200");
var settings = new ConnectionSettings(node);
var client = new ElasticClient(settings);
var descriptor = new BulkDescriptor();
descriptor.IndexMany(products, (bd, q) => bd.Id(q.id).Index("products"));
client.Bulk(descriptor);
The sample product class I'm using:
public class Product
{
public string id { get; set; }
public string nameEn { get; set; }
public string nameFr { get; set; }
}
Result as shown in Kabana:
id: nameEn: nameFr: _id:C _type:productsearch _index:products _score:1
Note how the id field is empty, but the Elasticsearch _id field is defined correctly.
Thanks for any help!

Entity Framework : adding record with related data

I have a very simple Situation with 2 tables
public class Movie
{
[Key]
public Guid ID { get; set; }
public string Name { get; set; }
public byte[] Hash { get; set; }
public int GenreID{ get; set; }
[ForeignKey("GenreID")]
public virtual Genre genre{ get; set; }
}
and
public class Genre
{
public int ID { get; set; }
public string Name { get; set; }
}
Now, in an import sequence I want to create new movies and link the Genre with the existing entries in the Genre table or create new Genre entries if they don't exist.
Movie m = new Movie();
m.ID = Guid.NewGuid();
IndexerContext db = new IndexerContext();
var genre = db.Genre.Where(g => g.Name== genreValue).FirstOrDefault();
if(genre!= null)
{
m.GenreID= genre.GenreID;
}
else
{
genre= new Genre();
genre.Name = genreValue;
db.Genres.Add(genre);
var genreCreated= db.Genre.Where(g => g.Name== genreValue).FirstOrDefault();
m.GenreID= genreCreated.GenreID;
}
Now the problem is, it doesn't work. The last line fails because genreCreated is null.
Plus I think I must doing it wrong - it can't be that difficult in Entity Framework.
can anyone help me?
db.Genres.Add(genre);
This does not send insert statement to database - this instructs entity framework that new record should be inserted when saving changes. Genre will be saved (and created id available) after you call db.SaveChanges(); As for now, you do not have save call, so genreCreated is null.
In your situation - fix is simple, you do not need to select genreCreated from db. Just setting m.Genre to new value should do the job
Movie m = new Movie();
m.ID = Guid.NewGuid();
IndexerContext db = new IndexerContext();
var genre = db.Genre.Where(g => g.Name== genreValue).FirstOrDefault();
if(genre! = null)
{
m.GenreID = genre.GenreID;
}
else
{
genre = new Genre();
genre.Name = genreValue;
m.Genre = genre;
}
db.SaveChanges(); //m.GenreID will automatically be set to newly inserted genre
After the add statement you need to save it:
Try
genre= new Genre();
genre.Name = genreValue;
db.Genres.Add(genre);
db.SaveChanges();

Simple DropDownList in ASP.NET MVC3 app

I need simple DropDownList in form and I don't want to create something like ViewModel.
I have two models(tables) in relation 1:n:
public class Course
{
public int ID { get; set; }
public string Name { get; set; }
}
and
public class Project
{
public int ID { get; set; }
public int CourseId { get; set; }
public int ProjectNo { get; set; }
public string Name { get; set; }
public DateTime Deadline { get; set; }
}
In the 'Create Project' I want to have DropDownList with Id (as value) and Name(as text) from Course table(model). In the new project will be insert chosen CourseId. How can I do that as simple as possible?
Any particular reason why you don't want to use a ViewModel? They're very helpful for this type of problem.
If you don't want to use a ViewModel, then you can construct a specific class in your controller that is an aggregate of the properties you need from both classes:
public ActionResult Show(int id)
{
Course course = repository.GetCourse(id); // whatever your persistence logic is here
Project project = projectRepository.GetProjectByCourseId(id);
string CourseName = from c in course where
c.ID == project.courseID
select c.Name;
IEnumerable<SelectListItem> selectList =
from c in course
select new SelectListItem
{
Selected = (c.ID == project.CourseId),
Text = c.Name,
Value = project.CourseId.ToString()
};
//add the selectList to your model here.
return View(); //add the model to your view and return it.
}
It would be far easier to have a ViewModel for this, so you could have a strongly typed view. Let me show you:
public class ProjectCourseViewModel
{
public SelectList ProjectCourseList {get; private set; }
public Project Project {get; private set; }
public Course Course {get; private set; }
public ProjectCourseViewModel(Project project, Course course)
{
ProjectCourseList = GetProjectCourseSelectList(project, course)
Project = project;
Course = course;
}
private SelectList GetProjectCourseSelectList(Project project, Course course)
{
IEnumerable<SelectListItem> selectList =
from c in course
select new SelectListItem
{
Selected = (c.ID == project.CourseId),
Text = c.Name,
Value = project.CourseId.ToString()
};
}
}
And then your controller would be really simple:
public ActionResult Show(int id)
{
Course course = repository.GetCourse(id);
Project project = projectRepository.GetProjectByCourseId(id);
ProjectCourseViewModel pcvm = new ProjectCourseViewModel(project, course)
return View(pcvm);
}
And then your view takes in a strongly typed model, and you don't have to rely on ViewData, which is a Good Thing.
Note: I haven't compiled this, just written it. There are probably compilation bugs.
probably you could solve it using the following example:
in your controller include a Viewbag
{
Viewbag.Course = db.course.ToList();
var project = new project.....
}
And in your View use the following pattern:
#Html.DropDownList("CourseId",
new SelectList(ViewBag.Course as System.Collections.IEnumerable,
"CourseId", "Name", Model.ID))
where each field represent:
•The name of the form field (CourseId)
•The list of values for the dropdown, passed as a SelectList
•The Data Value field which should be posted back with the form
•The Data Text field which should be displayed in the dropdown list
•The Selected Value which is used to set the dropdown list value when the form is displayed
more info at: http://www.asp.net/mvc/tutorials/mvc-music-store-part-5
brgds.
In the Controler:
var CourseName = from c in course where
c.ID == project.courseID
select c.Name;
SelectList sl = new SelectList(CourseName);
ViewBag.names= sl;
in the view :
#Html.DropDownList("Name", (SelectList)ViewBag.names)

Resources