ASP .NET database-first picklist field - c#

I want to create database table field which needs to have certain value.
For example field called season can have value:
spring, summer, autumn or winter.
public int id { get; set; }
public string season { get; set; }
public int yearNumber { get; set; }
public string season {get; set; }?
Could anyone help me? I'am aware that this question might be a little noobish but I am a totall newbie in ASP .NET not talking about web development...

Create a new table called Season.
Reference this table with Foreign-Key relationship.
This is a one-to-many relationship. Each of your Seasons can have many records in the other table.
In this case you should likely create another table that contains the 4 seasons. Often (but not always) you'll want to create an integer Id for each of those seasons, but you could just use the season's name as the Id (a varchar). You would reference this id as a Foreign Key. This is known as a Foreign Key relationship in Relational Databases (RDMS's), and it's used to Normalize the database. Normalization is what prevents you from repeating data (among other things) over and over, which can sometimes lead to data corruption It can be a little daunting if you're new to it, but it's a good thing to know.
http://blog.sqlauthority.com/2008/09/08/sql-server-%E2%80%93-2008-creating-primary-key-foreign-key-and-default-constraint/

Related

have primary key set up but says it is not defined?

before you link to another post, i am using migrations and all that i can find don't use the way i have to do it.
first this is homework,
second here is a link to a google drive with the "full" project project fill stuff that was given to help, and a word doc with specifications(but the last one is not as important)
so on to the problem i am tring to do my homework the package manager says this "The entity type 'Categories' requires a primary key to be defined. If you intended to use a keyless entity type call 'HasNoKey()'." almost no matter what i do. i can get it to stop but then the database is not actual made at all.
my teacher is not responing to my emails and the other students in my class that have responed have the same issue, and this is the very beginning of the project and for the last few days i have been stuck here so please help.
i will add edit as questions get asked, i am panicking on getting this done in time so i don't know what is important or not.
First of all, double check you actually set PrimaryKey on your Database table. Then use [Key] attribute from System.ComponentModel.DataAnnotations namespace.
public class Categories
{
[Key]
public string CategoryId { get; set; }
public string Name { get; set; }
}
And also, next time, make sure your ID fields are either numeric or Guid and auto generated by database identity specification.. string Ids are slow for querying db records and to index tables.
Must tell model CategoryId is key. Best to use int as type.
[Key]
public int CategoryId { get; set; }

Entity Framework Core: Persisting One-To-Many without existing foreign Entity

Having recently moved to C#/.Net Core from other languages, I got stuck on a problem with EF Core that I couldn't figure out from the documentation and hope you may be able to help. In a way this is related but not identical to my previous question .Net Core [FromBody] JArray to ICollection
My database holds a number of appointments that are rendered on a Syncfusion schedule. Attendees can be invited to these appointments. To facilitate that, a list of users is displayed in the editor and a JSON array of guids is transmitted with any insert or update action.
The User entity itself is not available within the scope of the application, so I'd like to persist only their Guids for each appointment. I had foreseen this structure:
Appointments (Start, End, ..., ´ICollection Attendees´)
Attendee would simply consist of AppointmentsId and Guid -
Since any one Guid can only attend each Appointment once, a composite Key made up of these two attributes appeared to be useful.
Any appointment can have none, one or many associated Guids.
In Code, I have this (abbreviated):
public class Appointment
{
public int Id { get; set; }
public DateTime StartTime { get; set; }
public ICollection<Attendee> AttendeeList { get; set; }
[NotMapped]
public List<Guid> PostedAttendeeList { get; set; } // Contains a list of Guids after an Insert/Update POST action from [FromBody]
}
Attendee would simply be made up of the Appointment Id and a Guid of a user.
public class Attendee
{
public Guid Id { get; set; }
public int AppointmentId { get; set; }
}
Attendee's configuration is this:
public class AttendeeConfiguration : IEntityTypeConfiguration<Attendee>
{
public void Configure(EntityTypeBuilder<Attendee> builder)
{
builder.HasKey(x => new { x.Id, x.AppointmentId });
}
}
After receiving a POST from the schedule, ´PostedAttendeeList´ may be empty or contain one or more Guids.
If it is an existing Appointment, ´AttendeeList´ may be empty or contain one or more Guids.
I'm wondering about a few things:
a) is there a better way to go about persisting this kind of data? I've tried to understand Owned Entity Types but failed to see if that would help me here.
b) if this is indeed an ok way to handle this, how can I make sure that ´AttendeeList´ is identical to ´PostedAttendeeList´ after processing, so that all new entries are added and those not present in ´PostedAttendeeList´ are removed through EF Core?
I'm especially confused about whom's responsibility it is to maintain ´AppointmentId´ - I wanted to keep the property visible but I understand that EF would fill that in when operating within the base property? Ie. that within the class ´Appointment´, a ´AttendeeList.Add(new Attendee() { Id = "1234-abcd-..." }´ would automagically fill in the AppointmentId upon saving?
If you read until here and are confused, please take a moment to remember when you started programming - I'm thoroughly confused and unable to come up with a better question. Even if you cannot help out with an answer, maybe you could help me make the question better. Thank you all very much! Any comment with suggestions will result in an update to my question in order to improve it.

Want to know about database design and best practice of table relationship

At first I want to give an example. Here I will use code first approach to make database tables and their relationship. Please look at the class below. (C#)
public class Blog
{
public int BlogId { get; set; }
public string Name { get; set; }
public virtual List<Post> Posts { get; set; }
}
public class Post
{
public int PostId { get; set; }
public string Title { get; set; }
public string Content { get; set; }
public int BlogId { get; set; }
public virtual Blog Blog { get; set; }
}
You’ll notice that I'm making the two navigation properties (Blog.Posts and Post.Blog) virtual. This enables the Lazy Loading feature of Entity Framework. Lazy Loading means that the contents of these properties will be automatically loaded from the database when you try to access them.
Now Here is my question.
I want to make a Database as like below. The table names will be:
tblCompany
tblSite // Site will be create under Company (A Company will have one or more Sites).
tblLine // Line will be create under Site (A Site will have one or more Lines).
tblMachine // Machine will be create under Line (A Line will have one or more Machines).
So I will create,
Company table and it will have a Company_Id.
.
Then I will create,
Site table and this table will have Site_Id and Company_Id for making relationship between Site Table and Company Table
.
After that when I create Line Table should I user both Company_Id
and Site_Id?
I know I can use only Site_Id and by query I can get the Site which Company belongs to. But what is the best practice? Should I use every Table's Id or I just use Previous Table's Id?
And also provide the class if anyone can.
No, you shouldn't have every table in a hierarchy having every ID from every table above it, because we can use joins to link the tables together in the entire hierarchy chain.
There may be a very limited number of situations where it's specifically advantageous to have a lower level table have the ID of one much further above it, embedded within it but it's typically a developer convenience, when they think "I can't be bothered joining these 27 tables together every time I want to know which machine belongs to which company. I'll just have a companyid in the machine table and I promise I'll keep it updated by some complicated mechanism"..
.. Don't do it.. when you sell a site to another company you have to remember to transfer all the machines to them too, not just by selling the site, but visiting every machine and updating its company ID, otherwise the hierarchy gets messed up
What's the alternative, if your front end app will be querying a million times a second which machines belong to which company, and you don't want the database to have to join 27 tables together, a million times a second, to find this out? Caching; a separate system where you maintain a transient list of machines and companies. Every time you sell something or make a transfer, you invalidate the cache when you update the part of the database hierarchy. Upon next query, the cache misses and shall be rebuilt with the new info. The database only occasionally has to join 27 tables
This is starting to head into an opinion piece, and hence heading out of scope of a SO question/answer, but if you come up against specific problems as you implement your system, feel free to post them up
Ps: don't prefix your tables with tbl; it's obvious what they are. The days of having to give everything a name that included the type of thing it was have thankfully long gone

Choosing name of column in entity framework code-first migrations

I have seen similar questions to this; but none quite the same; and none have helped me. I want the migration to use a different name for the column than I have for the property in my class. On built-in types, I am able to do this with [Column("newName")]. However, this doesn't work when I want a foreign key to another class.
In other words, this works just fine:
[Column("NameInDB")]
public string NameInCode { get; set; }
But this doesn't work at all:
[Column("Employee_Id")]
public virtual Employee Owner { get; set; }
In the second case, the migration still creates the column as Owner_Id; it completely ignores the Column annotation. Is there somewhere that it says that the Column annotation only works for built-in types? I couldn't find anything about that.
I know that it is possible to use the [ForeignKey] annotation to do this, but if I do, I have to have an extra property in my code that I don't want:
[ForeignKey("Employee_Id")]
public virtual Employee Owner { get; set; }
public int Employee_Id { get; set; }
I don't want to do that because the Employee_Id property is redundant in that case; I'd rather just use the Owner property. Is there a way around this, or a good reason that [Column] seems to be ignored?
public virtual Employee Owner { get; set; } is not mapped to DB, it is not represented in database. It populated by Entity Framework automatically for your convenience. Employee_Id - this is what is stored in DB. Entity Framework uses Employee_Id field to create Owner object. So, Emplyee_Id is not redundant in that case, it is mandatory and it has physical representation in DB, but Owner field is logical part of the class, managed by Entity Framework and not have it's column in DB. Makes sense?

Entity Framework storing arrays of data

I've started playing around with using Entity Framework Code-First because it looks like a nice way to get a database up and running quickly. I'm coming from a PostgreSQL background, which has support for array types in tables, for example time[]. My question is two-fold; does SQL Server support array types, and if so, how can I use them in EF? If they're not supported, what is an alternative way to represent this data?
table Venue
openhours time[]
Edit: The array above is intended to store different times for each day of the week- a venue might have different opening hours on different weekends to weekdays, for example.
No, it is not supported, you need to store your openhours in a separate table (VenueOpenhours) with a foreign key to the Venue table.
SQL Server doesn't support array types. Extrapolating from your example schema, I think an equivalent EF POCO would be the following:
public class Venue
{
public int VenueId { get; set; }
public DateTime OpenHour { get; set; }
public DateTime CloseHour { get; set; }
}
Finding whether the Venue was open at a given time would just require a range query, Venue.Where(a => a.OpenHour <= time && a.CloseHour >= time). Of course, this is a very simplistic example. Most likely you'd want to store the Venue hours in another table. But I hope this may be able to move you in the right direction.

Categories

Resources