appreciate your help and patience here! as I am a newbie to this and open to any new suggestion to achieve this!
So I have an Entity Candidate
which references another Entity Candimmigration
. I would like to Bind a few properties "NOT all Properties" from Candidate
and Candimmigration
into a Datagrid view, therefore if the data changes, the datagridview data get updated automatically.
public partial class Candidate
{
[Key]
[Column("ID")]
public int Id { get; set; }
[StringLength(20)]
public string FirstName { get; set; } = null!;
[StringLength(20)]
public string? MiddleName { get; set; }
[StringLength(20)]
public string LastName { get; set; } = null!;
[Column(TypeName = "date")]
public DateTime? DateOfBirth { get; set; }
[StringLength(6)]
public string? Gender { get; set; }
// more properties
[InverseProperty("Candidate")]
public virtual Candimmigration Candimmigration { get; set; } = null!;
// more InverseProperties
}
public partial class Candimmigration
{
public int Id { get; set; }
public int CandidateId { get; set; }
public string? VisaNo{ get; set; }
public string? PassportNo { get; set; }
public string? PlaceOfBirth { get; set; }
// more properties
}
I would like to bind and show only the below properties in the datagridview. Is there a way to achieve this rather than creating a list .ToList
, then I have to recreate it every time data changes to refresh/reload the datagridview. Any suggestions for implementation, please?
Candidate.Id
Candidate.FirstName
Candidate.LastName
Candimmigration.VisaNo
The code below binds all Candidates
to the grid view , which is not the expected result.
_dbContext.Candidates.Load();
_dbContext.Candidates.Local.ToBindingList();
CodePudding user response:
And I cannot do LINQ projection as then it won’t be binding
this statement is only true, if you are using an anonymous type
no one is stopping you from projecting your type to a "bindable" type
something like this:
class CandidateModel
{
public int Id { get; set; }
public string FirstName { get; set; } = null!;
public CandimmigrationModel Candimmigration { get; set; } = null!;
}
class CandimmigrationModel
{
public int Id { get; set; }
public string? VisaNo{ get; set; }
}
class CandidateViewModel
{
private CandidateModel _candidateModel;
private CandimmigrationModel _candimmigrationModel;
public string FirstName
{
get => _candidateModel.FirstName;
set => _candidateModel.FirstName = value;
}
public string VisaNo
{
get => _candimmigrationModel.VisaNo;
set => _candimmigrationModel.VisaNo= value;
}
public CandidateViewModel(CandidateModel candidateModel, CandimmigrationModel candimmigrationModel)
{
}
}
to project to this type simple add
.Select(x => new CandidateViewModel(x, x.Candimmigration))