I am new to ASP.NET MVC, especially Entity Framework.
I am trying to save JSON data from external service to SQL server. I use Code First and it creates tables and inserts all records. But original ID values are changed to SQL auto generated ID value. For example, original ID 20050 become 1. Please check attached photos. I googled my problem and did not find a solution.
This is my fist time posting a question in stackoverflow too. Thanks in Advance.
you can set identity specification to false to that table usine DataAnnotations attribute.
[DatabaseGenerated(DatabaseGeneratedOption.None)];
public int ID { get; set; }
Than apply migration.
Related
I'm very much a beginner when it comes to database relationships hence what I suspect is a basic question! I have two database tables as follows:
Projects
id
company_id
name
etc...
rfis
id
project_id (foreign key is id on the Projects table above)
Number (this is the column I need help with - more below)
question
The relationships at the Model level for these tables are as follows:
Project
public function rfi()
{
return $this->hasMany('App\Rfi');
}
RFI
public function project()
{
return $this->belongsTo('App\Project');
}
What I'm trying to achieve
In the RFI table I need a system generated number or essentially a count of RFI's. Where I'm finding the difficulty is that I need the RFI number/count to start again for each project. To clarify, please see the RFI table below which I have manually created with the the 'number' how I would like it displayed (notice it resets for each new project and the count starts from there).
Any assistance would be much appreciated!
Todd
So the number field depends on the number of project_id in the RFI table. It is exactly the number of rows with project_id plus one.
So when you want to insert a new row, you calculate number based on project_id and assign it.
RFI::create([
'project_id' => $project_id,
'number' => RFI::where('project_id', $project_id)->count() + 1,
...
]);
What I understood is that you want to set the value of the "number" field to "1" if it's a new project and "increment" if it's an existing project. And you want to automate this without checking for it every time you save a new row for "RFI" table.
What you need is a mutator. It's basically a method that you will write inside the desired Model class and there you will write your own logic for saving data. Laravel will run that function automatically every time you save something. Here you will learn more about mutators.
Use this method inside the "RFI" model class.
public function setNumberAttribute($value)
{
if(this is new project)
$this->attributes['number'] = 1;
else
$this->attributes['number']++;
}
Bonus topic: while talking about mutators, there's also another type of method called accessor. It does the same thing as mutators do, but just the opposite. Mutators get called while saving data, accessors get called while fetching data.
i have my sql server database and i used "generate persistence mapping" in intellij to get my java classes, but the relationships defined on my sql server database were not mapped, it seems i can add them with the "add relationship" but i have a lot of tables with a lot of relationships so it is a pain in the ass to do it...
is there something that can map the database including the relationships? for example if i have a table user with a defined relationship of type one to many with a table potatoes, get a java class like this :
public class user{
private int iduser;
private String name;
private String password;
//relationship!!
private ArrayList<Potatoes>potatoes; //this is mapped like "private int id_potatoes" by intillij
public user(){}
//getters and setters
}
i´m using open JPA. amd i also can't find a way to auto generate DAO's with some basic methods (save, find, delete), i will have to code them myself!!! and im talking of atleast 40 tables!! it is ridiculous!!
i know there MUST be a way to do all this stuff automatically. oh, im using jsf 2, i dont know if that is relevant to this question anyway.
when you generate persistence mapping, just check the below box option
匚 Show default relationships
by this to generate , you will get the table relationships you want. Hope to help you :)
Asp.net MVC2: I have many dropdownlists in my mvc application. At first, I started by creating a table for each one with a unique ID and name and referring to them in the controllers and views. The application got bigger, and it was suggested that I use a lookup table, that contains lookuptype and lookupvalue as compound primary key and fill all the values for the dropdownlists in it. I've looked all over the internet, the only method used for mvc is one table for each dropdownlist! Can someone explain to me how I can implement it, and in detail please becoz I'm totally lost. A link to a tutorial would also be great.
I'm using vb.net and linq to sql.
Suppose your tables have columns ID, Name and Value. Now by having only one table that table would most probably look like this:
create table Lookup
(
LookupID int not null identity
primary key,
LookupTypeID int not null
references LookupType(LookupTypeID),
Name nvarchar(50) not null,
Value int not null,
unique(EnumTypeID, Name)
)
go
This table will make sure that within the same type names don't clash.
Anyway. You could of course have a similar application (not data) model class
public class EnumValue
{
public int Id { get; set; }
[Required]
public string Name { get; set; }
[Required]
public int Value { get; set; }
}
So whenever you get values of a certain type you can always generate an IList<EnumValue> of them and feed them to a particular drop down.
Since you didn't provide any valuable data this table and class could omit column/property Value, because depending on the inner workings it may not be needed at all. But you will know this best because you know your application requirements. Instead of this column/property only ID could do the trick.
I actually used a slightly different approach. I created a table that has a composite primary key, LookupName and LookupValue. Then in the datacontext I declared a method that takes the lookupname as a parameter, and then brings a list of lookupvalues whose lookupname match this parameter. In the original table (ex.Contact) I created a field called status, where the selected value will be saved. Then in the controller, I used viewdata to create dropdownlists.
Example: _db represents the datacontext
Viewdata('Status')= new selectlist(_db.Getlookupname('status'),'lookupname','lookupname')
and then in the view
html.dropdownlist('status')
I also named the dropdownlist with the same fieldname 'status' that is found in the target table 'Contact'.
And it worked, without any complexity or errors.
Thanks for the help. And I hope this will be helpful to someone else!
Here's a sort of tutorial on how to achieve a generic lookup service.
http://wtfperminute.blogspot.com/2011/02/working-with-reference-data-lookups.html
Similar to what you've done, but perhaps a bit more comprehensive.
I have a standard update happening via linq to sql but the data does not persist to the database.
I am using an auto-generated class via the .dbml file designer.
The update statement is below:
public static void UpdateEmailsInWorkingTable(Guid emailGuid, string modifiedEmail)
{
using (EmailDBDataContext DBContext = new EmailDBDataContext())
{
EmailAddress_Update EAUpdated = (from e in DBContext.EmailAddress_Updates
where e.EmailGuid == emailGuid
select e).SingleOrDefault();
EAUpdated.EmailAddress = modifiedEmail;
EAUpdated.IsValid = 'Y';
EAUpdated.UpdateFlag = true;
EAUpdated.LastChangedDtTm = DateTime.Now;
try
{
DBContext.SubmitChanges(ConflictMode.FailOnFirstConflict);
}
catch (ChangeConflictException ex)
{
// do stuff here
}
}
}
I looked through my auto-generated DataContext class and the only glaring difference is that the table in question EmailAddress_Update does not implement the two interfaces INotifyPropertyChanging and INotifyPropertyChanged that the other auto-generated entities do.
I am assuming that this is the cause of why the changes are not being persisted is it not???
To put it simply none of the Extensibility Method Definitions get generated for any part of this one class. If this is the cause of my problems, what in the database would be causing this to not auto-generate properly??
Thanks~
I posted this question on MSDN as well here: MSDN Linq to Sql if you wanted to see the replies. But I found part of the reason why the code doesn't generate.
Here is a piece from my MSDN response:
I created a small test table without a primary key and added it to the designer and sure enough it didn't generate any of the Extensibility methods for that instance.
So I then added a primary key to the same table and re-added it to the designer and sure enough all of the extensibility methods and change tracking events were generated.
My question now is why must there be a primary key for this stuff to auto-generate?
Ok so to answer my own question "My question now is why must there be a primary key for this stuff to auto-generate?" I found it in the book Pro LINQ written by Joe Joseph C. Rattz, Jr.
I was reading how to handle views versus tables and he says this:
"Because the entity classes generated for views do not contain entity class properties that are mapped as primary keys, they are read-only. If you consider that without primary keys, the DataContext has no effective way to provide identity tracking, this makes sense."
Mystery and problem solved.
While trying to use LINQ to SQL I encountered several problems.
I have table persons:
int ID
string firstName
string lastName
And table notes that has:
int ID
string noteText
string createdBy
datetime creationDate
int PersonID
PersonID is a foreign key and the relationship is 1:n
I tried to use LINQ to SQL to create a person and some notes for each person.
Person person = new person();
Person.firstName = "me";
Person.note = new note();
Person.note.noteText = "some text…";
_DataContext.Persons.InsertOnSubmit(person);
_DataContext.SubmitChanges();
The problem is that the person object doesn't yet exist in the DB so it doesn't have an ID yet. So the note.personID filed has a 0 value… (the ID field is an identity field in the sql server)
The only solution for this that I found is to create a person , submitchanges and then create a note and submitchanges again.
Am I missing something here or maybe that’s the way one should work with LINQ to SQL?
How can I add multiple notes per person with LTS? I have a 1:n relationship and I don't see it with LTS.
If a person has 10000 notes, I don't want the person object constructor to load all the notes he has. I want to load them only when I refer to them. How can I config LTS to load the notes on demand?
If you aren't using the LinqToSql class designer, you should think about using it. The classes it generates will support the insertion scenario you outlined.
I can tell you aren't using the designer because it would give you a Notes (plural) property on the Person... as Person is 1 to Many with Notes.
How can I config LTS to load the notes on demand?
The designer will generate a property of type EntitySet(Note), which will load Notes on demand.