how to initialise a public property - c#-3.0

now how to initialise a value for it.
I know that i can initialise a property as
private int _formId=1;
public int FromID
{
get
{
return _formId;
}
set
{
_formId= value;
}
But if i create a property as
public int FromID { get; set; }
How can i initialise its value

You could initialize it in the constructor of your class:
public class Foo
{
public Foo()
{
FromID = 1;
}
public int FromID { get; set; }
}

public int FromID { get; set; }
is a short hand for the first piece of code.
If you need to set a value use the first piece of code

Related

EF Core 6 Seeding Data Gives Foreign Key error Despite Having FK Value

So, I have struggled with this for a while now and can't figure out what I'm missing. I have a table that holds an entity called Skill and the DataModel looks like this:
public class SkillModel
{
public SkillModel()
{
}
public SkillModel(int skillId)
{
SkillId = skillId;
}
public int SkillId { get; set; } = 0;
public string Name { get; set; } = "";
public Guid DescriptionId { get; set; } = new();
public int SkillGroupId { get; set; } = 0;
public SkillGroupModel SkillGroup { get; set; } = new();
}
It references the SkillGroup which is it's own table and it looks like this:
public class SkillGroupModel
{
public SkillGroupModel()
{
}
public SkillGroupModel(int skillGroupId)
{
SkillGroupId = skillGroupId;
}
public int SkillGroupId { get; set; } = 0;
public string Name { get; set; } = "";
public Guid DescriptionId { get; set; } = new();
public List<SkillModel> Skills { get; set; } = new();
}
They each have their own configuration files and the look like this:
SkillModel
public class SkillConfiguration : IEntityTypeConfiguration<SkillModel>
{
public void Configure(EntityTypeBuilder<SkillModel> builder)
{
var dataSeeds = new DataSeeds();
builder.ToTable("Skills", "Skills");
builder.HasKey(k => k.SkillId);
builder.HasOne(s => s.SkillGroup)
.WithMany(s => s.Skills);
builder.HasData(dataSeeds.Skills);
}
}
SkillGroupModel
var dataSeeds = new DataSeeds();
builder.ToTable("SkillGroups", "Skills")
.HasKey(k => k.SkillGroupId);
builder.HasData(dataSeeds.SkillGroups);
Data seeds looks like this:
SkillGroupModel Seed
public List<SkillGroupModel> GetSkillGroups()
{
return new List<SkillGroupModel>()
{
new()
{
SkillGroupId = 1, Name = "Artisan", DescriptionId = SkillGroupDescriptions["Artisan"].Id
},
...
}
SkillModel Seeds
return new List<SkillModel>()
{
new()
{
SkillId = 1,
Name = "Aesthetics",
DescriptionId = SkillDescriptions["Aesthetics"].Id,
SkillGroupId = 1
},
...
}
So, I was obviously missing something. Ivan Stoev had a great point of not initializing my navigation properties like that, and that was a great help.
I went about it by not using my navigation properties and only setting the FK Properties. I think in the past I was trying to do both and that was causing issues that took me down this path. I'm not sure what I was doing wrong before but the way the documentation for seeding data on MSDN worked fine for me after going back and trying it again.

Entity cannot load data from related class

i have 3 class like that and i used code first entity on .net
public class PersonModel
{
[Key]
public int PersonID { get; set; }
public string FullName { get ; set ; }
public string Phone { get ; set ; }
public string Adress { get; set ; }
public int NationalNumber { get ; set ; }
public List<SpecialtyToPersonModel> SpecialtyToPerson { get ; set ; }
}
public class SpecialtyModel
{
[Key]
public int SpecialtyID { get; set; }
public string SpecialtyName { get; set; }
public List<SpecialtyToPersonModel> SpecialtyToPerson { get; set; }
}
public class SpecialtyToPersonModel{
[Key]
public int SpecialtyToPersonID { get ; set ; }
public SpecialtyModel Specialty { get; set; }
public PersonModel Person { get;set; }
}
when i need to use specialityToPersonModel like this
var db = new EntityContext();
var aaa = db.SpecialtyToPersons;
return aaa.ToList(); // so Simple !
or like this :
var db = new EntityContext();
var aaa = db.SpecialtyToPersons
.Include(x=>x.Specialty)
.Include(x=>x.Person);
return aaa.ToList();
, it throw me out with this error :
Error Picture
An exception of type 'Npgsql.PostgresException' occurred in Microsoft.EntityFrameworkCore.dll but was not handled in user code: 'External component has thrown an exception.'
its my fault that make DB bad at first , its from db not code ...
i correct my code and run
dotnet ef migrations add InitialCreate
and
dotnet ef database update
again and so on ... Ty Anyway ...
So shouldn't SpecialtyToPersonModel look more like this
Public Class SpecialtyToPersonModel{
[Key]
Public int SpecialtyID { Get; Set; }
Public SpecialtyModel Specialty { Get; Set; }
Public int PersonID { Get; Set; }
Public PersonModel Person { Get;Set; }
}

Should DbSets of nested classes be defined in DbContext?

Consider the following code:
public class MainObject
{
public int Id { get; set; }
List<NestedObject> NestedObjects { get; set; }
}
public class NestedObject
{
public int Id { get; set; }
public string Name { get; set; }
}
public class ExampleContext : DbContext
{
DbSet<MainObject> MainObjects { get; set; }
// Should it be here? Code works without it...
// DbSet<NestedObject> NestedObjects { get; set; }
}
// ( ... )
var nestedFooObjects = exampleContext.Get<NestedObject>()
.Where(obj => obj.Name == "foo").ToList(); // still works
I was under the impression that a DBContext should contain all tables that are directly accessed from code. So without DbSet< NestedObject > it should only be possible to get MainObjects and then look for NestedObjects within the main ones. That is not the case apparently, as my experiments show. I want to get NestedObjects directly as in the example above. In that case: Should DbSet< NestedObject > be defined at all? Its not necessary for the code to run...

SetValue to properites from inherited class

I need to create a generic set accesor where i can pass the classname.classname.property and the value to be set.
I saw this question and has been answered but i can't implement it on my project.
link is Is it possible to pass in a property name as a string and assign a value to it?
In the sample code below, how can SetValue set a value for length and width?
public interface MPropertySettable { }
public static class PropertySettable {
public static void SetValue<T>(this MPropertySettable self, string name, T value) {
self.GetType().GetProperty(name).SetValue(self, value, null);
}
}
public class Foo : MPropertySettable {
public Taste Bar { get; set; }
public int Baz { get; set; }
}
public class Taste : BarSize {
public bool sweet {get; set;}
public bool sour {get; set;}
}
public class BarSize {
public int length { get; set;}
public int width { get; set;}
}
class Program {
static void Main() {
var foo = new Foo();
foo.SetValue("Bar", "And the answer is");
foo.SetValue("Baz", 42);
Console.WriteLine("{0} {1}", foo.Bar, foo.Baz);
}
}
You are trying to set a string value to a Taste object.
It works fine using a new instance of Taste
class Program {
static void Main() {
var foo = new Foo();
foo.SetValue("Bar", new Taste());
foo.SetValue("Baz", 42);
Console.WriteLine("{0} {1}", foo.Bar, foo.Baz);
}
}
It will work if BarSize would derive from MPropertySettable.
public interface MPropertySettable { }
public static class PropertySettable
{
public static void SetValue<T>(this MPropertySettable self, string name, T value) {
self.GetType().GetProperty(name).SetValue(self, value, null);
}
}
public class Foo : MPropertySettable
{
public Taste Bar { get; set; }
public int Baz { get; set; }
}
public class Taste : BarSize
{
public bool sweet { get; set; }
public bool sour { get; set; }
}
public class BarSize : MPropertySettable
{
public int length { get; set; }
public int width { get; set; }
}
class Program
{
static void Main() {
var barSize = new BarSize();
barSize.SetValue("length", 100);
barSize.SetValue("width", 42);
Console.WriteLine("{0} {1}", barSize.length, barSize.width);
}
}

Static Class Property getting NULL when Custom Validation fired in Silverlight 4 - MVVM

1. I have created Test Class which contain Static Class and Property.
namespace QSys.Data.Domain.DataSecurity
{
public static class TestData
{
public static string MyName { get; set; }
}
}
2. Customer Model class and Custom Validation
namespace QSys.Data.Domain
{
[Serializable()]
public class Customer
{
[Key]
public virtual int Id { get; set; }
[CustomValidation(typeof(CustomerRequiredRules), "IsCompanyNameEmpty")]
public virtual string CompanyName { get; set; }
public virtual string City { get; set; }
}
public class CustomerRequiredRules
{
public static ValidationResult IsCompanyNameEmpty(string CompanyName, ValidationContext context)
{
if (TestData.MyName == "Imdadhusen")
{
return new ValidationResult("Company name not allowed!", new string[] { "CompanyName" });
}
return ValidationResult.Success;
}
}
}
3. Setting value of Static class like
public class AdminHomeViewModel
{
public AdminHomeViewModel()
{
TestData.MyName = "Imdadhusen";
}
}
4. I click on submit button, my custom validation getting fired and here i couldn't able to get value of TestData.MyName. it will display Null instead of Imdadhusen.
Any Answer, Suggestion or Comment highly appreciated!
Thanks,
Imdadhusen