Cannot drop a constraint in MS ACCESS - ms-access-2003

When using the SQL command :
ALTER TABLE [Sessions] DROP CONSTRAINT [SessionAttendance]
I get the exception error message "Could not find reference."
The constraint exists, and shows in the system table of constraints for this user table. How can I get this constraint to drop?
The database is in MS-ACCESS 2003 format. The application uses JET 4.0 I have several hundred instances which will need schema updates. I have a utility program to generate the SQL, but it falls over when attempting the DROP CONSTRAINT action.

Answered by implications of Gord Thompson in comment suggestions.
The ALTER statement was being applied to the wrong table in the relation.
The constraint was originally Added to the Attendance table. However it shows up as an attribute of the Sessions table when using the "GetOleDbSchemaTable" method to list.
Per the following code excerpt:
Structure Relation
Public Name As String
Public PrimaryTableName As String
Public PrimaryField As String
Public PrimaryIndex As String
Public ForeignTable As String
Public ForeignField As String
Public OnUpdate As String
Public OnDelete As String
Public Overrides Function ToString() As String
Dim msg As String = String.Format("Name:{0} PT:{1} PF:{2} PI:{3} FT:{4} FF:{5}", _
Name, PrimaryTableName, PrimaryField, PrimaryIndex, ForeignTable, ForeignField)
Return msg
End Function
End Structure
Private Function ListRelations(tableName As String) As List(Of Relation)
Dim relations As New List(Of Relation)
Dim MySchemaTable As DataTable
Dim dbConn As New OleDbConnection(connectionString)
dbConn.Open()
MySchemaTable = dbConn.GetOleDbSchemaTable(OleDbSchemaGuid.Foreign_Keys, _
New Object() {Nothing, Nothing, tableName})
Dim result As Boolean = False
'List the table name from each row in the schema table.
For Each row As DataRow In MySchemaTable.Rows
Dim r As New Relation
r.Name = row("FK_NAME")
r.PrimaryTableName = row("PK_TABLE_NAME")
r.PrimaryField = row("PK_COLUMN_NAME")
r.PrimaryIndex = row("PK_NAME")
r.ForeignTable = row("FK_TABLE_NAME")
r.ForeignField = row("FK_COLUMN_NAME")
r.OnUpdate = row("UPDATE_RULE")
r.OnDelete = row("DELETE_RULE")
Console.WriteLine(r.ToString)
relations.Add(r)
Next
MySchemaTable.Dispose()
dbConn.Close()
dbConn.Dispose()
Return relations
End Function

Related

Inserting columns in Sqlite database using android studio

Inserting columns in Sqlite database using android studio and on how to set some as autoincrement and primarykeys
If you set the column type as INTEGER PRIMARY KEY and if you do not specify a value when inserting a row, then a value (64bit signed integer) will be assigned an unused integer, usually one greater then the largest.
You very likely do not need to use the AUTOINCREMENT keyword (this assigns an integer that is unique within the database, rather than at the table level and thus has overheads in determining that integer).
Frequently _id is used, so will will often see
db.execSQL("CREATE TABLE tablename (_id INTEGER PRIMARY KEY, column_name column_type, ...more column_name / column_types as required...);");
As an example, the following code uses a subclass of SQLiteOpenHelper (not needed but frequently used), which requires an onCreate method (which is called when the database is created e.g. the very first time the helper is used) and an onUpgrade method (required if the version number is incremented/increased).
This code will create, if need be, a database called mydb (filename mydb.sqlite for Operating Systems that support extension greater than 3 characters).
Note if need be is just once (with some rare exceptions) unless the database is deleted. i.e. onCreate is not called every time an instance of the helper is constructed, it is only called when the database file itself doesn't exist (again rare exceptions apply).
It will then, if creating the database, create a table in the database named testfloat. The table will consists of 2 columns namely, _id and myfloat.
The _id column type is INTEGER PRIMARY KEY, if when inserting a row and no value is specified for the column then it will be a unique incrementing integer (1 at first, then 2 ......).
The myfloat column is of type FLOAT (perhaps checkout Datatypes In SQLite Version 3 for SQLite's flexibility in regards to Datatypes), if a value isn't given when inserting a row then a value of 0.0 will be given.
public class MyDBHelper extends SQLiteOpenHelper {
public static final String DBNname = "mydb";
public static final int DBVersion = 1;
public static final String TESTFLOATTABLE = "testfloat";
public static final String STDIDCOL = "_id INTEGER PRIMARYKEY";
public static final String MYFLOATCOL = "myfloat";
public static final String MYFLOATTYPE = " FLOAT DEFAULT 0.0";
public MyDBHelper(Context context) {
super(context,DBNname,null,DBVersion);
}
#Override
public void onCreate(SQLiteDatabase db) {
db.execSQL("CREATE TABLE " +
TESTFLOATTABLE +
"(" +
STDIDCOL +
"," +
MYFLOATCOL +
MYFLOATTYPE +
")");
}
#Override
public void onUpgrade(SQLiteDatabase db, int oldeversion, int newversion) {
}
public long insertRow(double myfloatvalue) {
long rv;
SQLiteDatabase db = getWritableDatabase();
ContentValues cv = new ContentValues();
cv.put(MYFLOATCOL,myfloatvalue);
rv = db.insert(TESTFLOATTABLE,null,cv);
return rv;
}
public Cursor getAllMyFloats() {
Cursor rv;
SQLiteDatabase db = getReadableDatabase();
rv = db.query(TESTFLOATTABLE,null,null,null,null,null,null);
return rv;
}
}
The code above, has an empty method for onUpgrade. Additionally there are two methods insertRow (to insert a row) and getAllMyFloats to return a Cursor, with in this case, all rows containing all columns.
In you invoking activity you could do something along the lines of :-
MyDBHelper mydbhelper = new MyDBHelper(this);
mydbhelper.insertRow(1.3);
mydbhelper.insertRow(1);
mydbhelper.insertRow(5.674389123459834);
The first line gets a MyDBHelper instance, which when first run will create the database and in doing so call the onCreate method, thus creating the tables.
The next three lines invoke the insertRow method (note if the app is rerun 3 additional rows will be added........ i.e. the code is for demonstration), which will cause 3 rows to be added, the first will have 1 in the _id column, the next 2 etc.
The following code (which follows on from the code above) demonstrates obtaining and interrogating a Cursor:-
Cursor getfloats = mydbhelper.getAllMyFloats();
Log.d("TESTFLOAT","Rows returned from getALlFloats = " + getfloats.getCount());
while (getfloats.moveToNext()) {
Log.d("TESTFLOAT","Via getString = " + getfloats.getString(getfloats.getColumnIndex(mydbhelper.MYFLOATCOL)));
Log.d("TESTFLOAT","Via getFloat = " + Float.toHexString(
getfloats.getFloat(
getfloats.getColumnIndex(
mydbhelper.MYFLOATCOL
)
)
));
Log.d("TESTFLOAT","Via getDouble = " +Double.toString(
getfloats.getDouble(
getfloats.getColumnIndex(
mydbhelper.MYFLOATCOL
)
)));
}
getfloats.close();
The first line invokes the getAllMyFLoats that returns a cursor.
The next line wtires a log message that details how many rows are in the resultant cursor.
The while clause transverses the cursor if there are any rows in the cursor. For each row it gets the value of the myfloat column, using some of the cursor.get????? methods (to demonstrate how getting the value is affected by each). Note instead of getfloats.get????(getfloats.getColumnIndex(column)), getfloats.get????(1) would work.

Why do my EntityFramework 6.1 Indexes using a custom DbInitializer not work?

I got a tiny model:
Public Class Thing
Public Property Id As Integer
Public Property Name As String
End Class
A matching DbContext:
Public Class Context
Inherits DbContext
Public Sub New()
MyBase.New("EfCodeFirstUniqueConstraintTest")
End Sub
Public Property Things As IDbSet(Of Thing)
Protected Overrides Sub OnModelCreating(modelBuilder As DbModelBuilder)
MyBase.OnModelCreating(modelBuilder)
BuildConstraints(modelBuilder)
End Sub
Private Sub BuildConstraints(modelBuilder As DbModelBuilder)
modelBuilder.Entity(Of Thing).Property(Function(m) m.Name) _
.HasMaxLength(255) _
.HasColumnAnnotation(IndexAnnotation.AnnotationName, _
New IndexAnnotation(New IndexAttribute("UniqueOrgUnitName") _
With {.IsUnique = True}))
End Sub
End Class
When I put this into a Solution with EF6.1 using this code:
Sub Main()
Using db As New Context
Dim t = New Thing With {.Name = "Thingy"}
db.Things.Add(t)
db.SaveChanges()
End Using
End Sub
everything works as expected. The 2. run will throw an exception for there is a unique index violation.
Unfortunately, I need my application to not throw away the whole DB. So I wrote a table and constraints dropping DbInitializer like this:
Public Class DbIniter
Implements IDatabaseInitializer(Of Context)
Public Sub InitializeDatabase(context As Context) Implements IDatabaseInitializer(Of Context).InitializeDatabase
DropAllTables(context)
Dim dbCreationScript = CType(context, IObjectContextAdapter).ObjectContext.CreateDatabaseScript()
context.Database.ExecuteSqlCommand(dbCreationScript)
CreateMetaDataTable(context)
Seed(context)
context.SaveChanges()
End Sub
Protected Sub DropAllTables(context As Context)
context.Database.ExecuteSqlCommand("EXEC sp_MSforeachtable 'ALTER TABLE ? NOCHECK CONSTRAINT all'")
Dim remainingTrys = 100
Dim everythingOk = False
While Not everythingOk AndAlso remainingTrys > 0
Try
context.Database.ExecuteSqlCommand("EXEC sp_MSforeachtable ""DECLARE #name nvarchar(max); SET #name = parsename('?', 1); EXEC sp_MSdropconstraints #name""")
context.Database.ExecuteSqlCommand("EXEC sp_MSforeachtable 'DROP TABLE ?'")
everythingOk = True
Catch ex As Exception
remainingTrys = remainingTrys - 1
End Try
End While
If Not everythingOk Then Throw New System.Data.Entity.Infrastructure.RetryLimitExceededException(String.Format("Database was not empty after last attempt."))
End Sub
Protected Sub CreateMetaDataTable(context As Context)
Dim sql = "CREATE TABLE dbo.__MigrationHistory ( MigrationId NVARCHAR(255) NOT NULL, CreatedOn DATETIME NOT NULL, Model VARBINARY(MAX) NOT NULL, ProductVersion NVARCHAR(32) NOT NULL);" _
& " ALTER TABLE dbo.__MigrationHistory ADD PRIMARY KEY (MigrationId); INSERT INTO dbo.__MigrationHistory (MigrationId, CreatedOn, Model, ProductVersion) VALUES ('InitialCreate', GetDate(), #p0, #p1);"
context.Database.ExecuteSqlCommand(sql, GetModel(context), GetProductVersion())
End Sub
Protected Function GetModel(context As Context) As Byte()
Using memoryStream As New MemoryStream
Using gzipStream As New GZipStream(memoryStream, CompressionMode.Compress)
Using writer = XmlWriter.Create(gzipStream, New XmlWriterSettings With {.Indent = True})
EdmxWriter.WriteEdmx(context, writer)
End Using
End Using
Return memoryStream.ToArray
End Using
End Function
Protected Overridable Sub Seed(context As Context)
End Sub
Protected Function GetProductVersion() As String
Return GetType(DbContext).Assembly.GetCustomAttributes(False).OfType(Of Reflection.AssemblyInformationalVersionAttribute).Single.InformationalVersion
End Function
End Class
Using this initializer, my indexes will never hit the database. Everything else works just fine.
ObjectContext.CreateDatabaseScript() will not return any SQL for the indexes:
create table [dbo].[Things] (
[Id] [int] not null identity,
[Name] [nvarchar](255) null,
primary key ([Id])
);
Using the default DbInitializer, the SQL sent to the DB looks like this:
CREATE TABLE [dbo].[Things] (
[Id] [int] NOT NULL IDENTITY,
[Name] [nvarchar](255),
CONSTRAINT [PK_dbo.Things] PRIMARY KEY ([Id])
)
followed by another statement like this:
CREATE UNIQUE INDEX [UniqueOrgUnitName] ON [dbo].[Things]([Name])
Does someone have any insight into why this does not work?
Where would the index-SQL come from when it is not included in what CreateDatabaseScript() does return?
I don't know exactly the history of EF but writing an EF provider (https://jetentityframeworkprovider.codeplex.com/) I've seen that some old EF versions used to generate object items using DbProviderServices interface. That interface (the interface you are using with your initializer) works on StoreItemCollection that I'm quite sure that does not contain information about indexes but only about EntitySet (entities) and AssociationSet (relationships). In the project above the implementation is in JetCreateSqlGenerator class.
Since some EF version, the EF does not use DbProviderServices anymore to generate database objects, or, better, if the EF Provider provides a MigrationSqlGenerator the EF uses that interface otherwise the EF use the old DbProviderServices. MigrationSqlGenerator provides Index generation and other migration utilities (for example column and table rename and so on).
So you don't see index generation in your custom migration because you are using the old interface.

Ebean Annotations - Using sequences to generate IDs in DB2

I'm trying to use sequences to generate incremented IDs for my tables in DB2. It works when I send SQL statements directly to the database, but when using ebean the statement fails. Here's the field in Java:
#Id
#GeneratedValue(strategy = GenerationType.SEQUENCE, generator = "TABLENAME_IDNAME_TRIG")
#SequenceGenerator(name = "TABLENAME_IDNAME_TRIG", sequenceName = "TABLENAME_IDNAME_SEQ")
#Column(name = "IDNAME")
private Long id;
Here's the column in SQL (From TOAD):
Name Data type Not Null Default Generated Bit Data Scope Identity
IDNAME INTEGER Yes No No
And here's the sequence definition in SQL:
CREATE OR REPLACE SEQUENCE SCHEMA.TABLENAME_IDNAME_SEQ
AS INTEGER CACHE 50 ORDER;
And the trigger:
CREATE OR REPLACE TRIGGER SCHEMA.TABLENAME_IDNAME_TRIG
NO CASCADE BEFORE INSERT
ON TABLENAME
REFERENCING
NEW AS OBJ
FOR EACH ROW
BEGIN
SET obj.IDNAME=NEXT VALUE FOR SCHEMA.TABLENAME_IDNAME_SEQ;
END;
What is the issue with my annotations here? As a(n important) side note - when I set GenerationType to AUTO, TABLE, or IDENTITY, it works, even though it shouldn't, because I'm also using this object to represent a parallel oracle table which also uses sequences for ID generation.
Edited to include error message:
javax.persistence.PersistenceException: Error getting sequence nextval
...
Caused by: com.ibm.db2.jcc.am.SqlSyntaxErrorException: DB2 SQL Error: SQLCODE=-348, SQLSTATE=428F9, SQLERRMC=NEXTVAL FOR SCHEMA.TABLENAME_IDNAME_SEQ, DRIVER=4.19.49
EDIT 2: The specific Sql statement that is failing is:
values nextval for QA_CONNECTION_ICONNECTIONI_SEQ union values nextval for QA_CONNECTION_ICONNECTIONI_SEQ union values nextval for QA_CONNECTION_ICONNECTIONI_SEQ
Which is SQL generated by Ebean. This is a smaller version of the real statement, which is repeated 20 times, so I'm guessing something screws up when generating the caching query.
EDIT 3: I believe this might be a bug in Ebean's use of DB2 sequences. This function generates SQl that returns an error for me when used with db2
public DB2SequenceIdGenerator(BackgroundExecutor be, DataSource ds, String seqName, int batchSize) {
super(be, ds, seqName, batchSize);
this.baseSql = "values nextval for " + seqName;
this.unionBaseSql = " union " + baseSql;
}
EDIT 4: Based on this SO link I think it is a bug.
Can't insert multiple values into DB2 by using UNION ALL and generate IDs from sequence
The correct class probably looks like this? Though I haven't ever tried building the library, so I couldn't test it. Time to learn how to open a defect I guess.
public class DB2SequenceIdGenerator extends SequenceIdGenerator {
private final String baseSql;
private final String unionBaseSql;
private final String startSql;
public DB2SequenceIdGenerator(BackgroundExecutor be, DataSource ds, String seqName, int batchSize) {
super(be, ds, seqName, batchSize);
this.startSql = "values "
this.baseSql = "(nextval for " + seqName);
this.unionBaseSql = ", " + baseSql;
}
public String getSql(int batchSize) {
StringBuilder sb = new StringBuilder();
sb.append(startSql);
sb.append(baseSql);
for (int i = 1; i < batchSize; i++) {
sb.append(unionBaseSql);
}
return sb.toString();
}
}
Temporary workaround for those interested: in ebean.properties, set
ebean.databaseSequenceBatchSize=1

EF6 Database First making Stored Procedure Async

What's the right way to run a EF6 stored procedure (database-first) in async mode?
I read about ToListAsync() but I don't see that available on stored procedure.
Also not sure if there is a different way to call the stored procedure when the actual call returns (#1) an OUT param or a (#2) list of items:
Case #1
using (DBContext db = new DBContext())
{
ObjectParameter result = new ObjectParameter("Result",
typeof(global::System.Boolean));
db.Login("email#email.com", "password", result);
}
Case #2
using (DBContext db = new DBContext())
{
var result = db.Contact_GetList("New York");
}
Thanks for the help
As per this workitem you would need to use SqlQueryAsync. Feel free to upvote the work item on the EF Codeplex site.
To map stored procedures and start using it with out writing any initial code, this is how I did it.
create a new model with a new connection string that will generate the connection string automatically in the web.config file where the connection string is at (if you use a current connection string it may no work when you test the function for the SP on the model browser).
map your table and the stored procedures (you can test the stored procedures in the model browser).
create classes that represents the attributes retrieved by each stored procedure e.g if your stored procedure returns three columns A,B,C, then the class must also have these three columns as attribute with the [key()] on top of the column that is going to be the PK
now create your controller with the class created and a new DbContext
then copy the information in the data context generated for the model and pasted in the new context that you generate when creating the controller.
when you want to use the store procedures they will be ready on the db.context because you paste their code on you new db-context that you create when the controller was crated.
NOTE: I hope this is not confusing but I can use the stored procedures with out typing any code, please ask me if you need sample code or screen shots, your new db-context will not over write after you created
This is the stored procedure I map
'--------------------------------------------------------------------------
' <auto-generated>
' This code was generated from a template.
'
' Manual changes to this file may cause unexpected behavior in your application.
' Manual changes to this file will be overwritten if the code is regenerated.
' </auto-generated>
'-----------------------------------------------------------------------
Imports System
Imports System.Collections.Generic
Partial Public Class phone_CurrentConferences_Result
Public Property AppointmentID As Integer
Public Property AppTitle As String
Public Property DateTime As Nullable(Of Date)
Public Property [Date] As String
Public Property Time As String
Public Property Company As String
Public Property Contact As String
Public Property Phone As String
Public Property Office As String
Public Property Lead_Director As String
Public Property TBD As Nullable(Of Boolean)
Public Property conference As String
End Class
This is the same model with a primary key
Imports System
Imports System.Collections.Generic
Imports System.ComponentModel.DataAnnotations
Public Class Conferences
[Key]
Public Property AppointmentID As Integer
Public Property AppTitle As String
Public Property DateTime As Nullable(Of Date)
Public Property [Date] As String
Public Property Time As String
Public Property Company As String
Public Property Contact As String
Public Property Phone As String
Public Property Office As String
Public Property Lead_Director As String
Public Property TBD As Nullable(Of Boolean)
Public Property conference As String
End Class
This is the context generated by the EF
'--------------------------------------------------------------------------
' <auto-generated>
' This code was generated from a template.
'
' Manual changes to this file may cause unexpected behavior in your application.
' Manual changes to this file will be overwritten if the code is regenerated.
' </auto-generated>
'--------------------------------------------------------------------------
Imports System
Imports System.Data.Entity
Imports System.Data.Entity.Infrastructure
Imports System.Data.Entity.Core.Objects
Imports System.Linq
Partial Public Class DayMasterEntities
Inherits DbContext
Public Sub New()
MyBase.New("name=DayMasterEntities")
End Sub
Protected Overrides Sub OnModelCreating(modelBuilder As DbModelBuilder)
Throw New UnintentionalCodeFirstException()
End Sub
Public Overridable Function phone_CurrentConferences(number As String, [date] As Nullable(Of Date)) As ObjectResult(Of phone_CurrentConferences_Result)
Dim numberParameter As ObjectParameter = If(number IsNot Nothing, New ObjectParameter("number", number), New ObjectParameter("number", GetType(String)))
Dim dateParameter As ObjectParameter = If([date].HasValue, New ObjectParameter("date", [date]), New ObjectParameter("date", GetType(Date)))
Return DirectCast(Me, IObjectContextAdapter).ObjectContext.ExecuteFunction(Of phone_CurrentConferences_Result)("phone_CurrentConferences", numberParameter, dateParameter)
End Function
End Class
SO, when I create the controller I use the model with the <KEY()> and I create my own context that will look like this
Imports System.Data.Entity
Imports System.Data.Entity.Infrastructure
Imports System.Data.Entity.Core.Objects
Namespace Models
Public Class DayMasterContext
Inherits DbContext
' You can add custom code to this file. Changes will not be overwritten.
'
' If you want Entity Framework to drop and regenerate your database
' automatically whenever you change your model schema, please use data migrations.
' For more information refer to the documentation:
' http://msdn.microsoft.com/en-us/data/jj591621.aspx
Public Sub New()
MyBase.New("name=DayMasterEntities")
End Sub
Protected Overrides Sub OnModelCreating(modelBuilder As DbModelBuilder)
Throw New UnintentionalCodeFirstException()
End Sub
Public Property Conferences As System.Data.Entity.DbSet(Of Conferences)
End Class
End Namespace
Then I copy the info in the context generated by the EF to my context
Imports System.Data.Entity
Imports System.Data.Entity.Infrastructure
Imports System.Data.Entity.Core.Objects
Namespace Models
Public Class DayMasterContext
Inherits DbContext
' You can add custom code to this file. Changes will not be overwritten.
'
' If you want Entity Framework to drop and regenerate your database
' automatically whenever you change your model schema, please use data migrations.
' For more information refer to the documentation:
' http://msdn.microsoft.com/en-us/data/jj591621.aspx
Public Sub New()
MyBase.New("name=DayMasterEntities")
End Sub
Protected Overrides Sub OnModelCreating(modelBuilder As DbModelBuilder)
Throw New UnintentionalCodeFirstException()
End Sub
Public Overridable Function phone_CurrentConferences(number As String, [date] As Nullable(Of Date)) As ObjectResult(Of phone_CurrentConferences_Result)
Dim numberParameter As ObjectParameter = If(number IsNot Nothing, New ObjectParameter("number", number), New ObjectParameter("number", GetType(String)))
Dim dateParameter As ObjectParameter = If([date].HasValue, New ObjectParameter("date", [date]), New ObjectParameter("date", GetType(Date)))
Return DirectCast(Me, IObjectContextAdapter).ObjectContext.ExecuteFunction(Of phone_CurrentConferences_Result)("phone_CurrentConferences", numberParameter, dateParameter)
End Function
Public Property Conferences As System.Data.Entity.DbSet(Of Conferences)
End Class
End Namespace
So, now you can use this context to query
entConferences(number As String, [date] As Nullable(Of Date)) As ObjectResult(Of phone_CurrentConferences_Result)
or to get a DBSet(of conferences)
Here is a controller I have created with this technique
Look where I call my stored procedure
Dim conferences = db.phone_CurrentConferences(phoneNumber, currentDate)
Imports System.Data
Imports System.Data.Entity
Imports System.Data.Entity.Infrastructure
Imports System.Linq
Imports System.Net
Imports System.Net.Http
Imports System.Web.Http
Imports System.Web.Http.Description
Imports BIWEBAPI
Imports BIWEBAPI.Models
Namespace Controllers.DayMasterControllers
Public Class ConferencesController
Inherits System.Web.Http.ApiController
Private db As New DayMasterContext
' GET: api/Conferences
Function GetConferences() As IQueryable(Of Conferences)
Return db.Conferences
End Function
' GET: api/Conferences/3053742500
''' <summary>
''' Use to get the current conferences selected by date
''' </summary>
''' <param name="id">phone number and date separated by coma ",""</param>
''' <returns>conferences by date</returns>
''' <remarks></remarks>
<ResponseType(GetType(Conferences))>
Function GetConferences(ByVal id As String) As List(Of Conferences)
Dim conferencelist = New List(Of Conferences)
Dim dateAndPhoneNumber = Split(id, ",")
Dim currentDate = ""
Dim phoneNumber = dateAndPhoneNumber(0)
If dateAndPhoneNumber.Length > 1 Then
currentDate = DateTime.Parse(dateAndPhoneNumber(1))
Else : currentDate = DateTime.Today
End If
Dim conferences = db.phone_CurrentConferences(phoneNumber, currentDate)
For Each conferenceInQuery As Object In conferences
Dim conference = New Conferences()
conference.AppointmentID = conferenceInQuery.AppointmentID
conference.AppTitle = conferenceInQuery.AppTitle
conference.DateTime = conferenceInQuery.DateTime
conference.[Date] = conferenceInQuery.[Date]
conference.Time = conferenceInQuery.Time
conference.Company = conferenceInQuery.Company
conference.Contact = conferenceInQuery.Contact
conference.Phone = conferenceInQuery.Phone
conference.Office = conferenceInQuery.Office
conference.Lead_Director = conferenceInQuery.Lead_Director
conference.TBD = conferenceInQuery.TBD
conference.conference = conferenceInQuery.conference
conferencelist.Add(conference)
Next
Return conferencelist
End Function
' PUT: api/Conferences/5
<ResponseType(GetType(Void))>
Function PutConferences(ByVal id As Integer, ByVal conferences As Conferences) As IHttpActionResult
If Not ModelState.IsValid Then
Return BadRequest(ModelState)
End If
If Not id = conferences.AppointmentID Then
Return BadRequest()
End If
db.Entry(conferences).State = EntityState.Modified
Try
db.SaveChanges()
Catch ex As DbUpdateConcurrencyException
If Not (ConferencesExists(id)) Then
Return NotFound()
Else
Throw
End If
End Try
Return StatusCode(HttpStatusCode.NoContent)
End Function
' POST: api/Conferences
<ResponseType(GetType(Conferences))>
Function PostConferences(ByVal conferences As Conferences) As IHttpActionResult
If Not ModelState.IsValid Then
Return BadRequest(ModelState)
End If
db.Conferences.Add(conferences)
db.SaveChanges()
Return CreatedAtRoute("DefaultApi", New With {.id = conferences.AppointmentID}, conferences)
End Function
' DELETE: api/Conferences/5
<ResponseType(GetType(Conferences))>
Function DeleteConferences(ByVal id As Integer) As IHttpActionResult
Dim conferences As Conferences = db.Conferences.Find(id)
If IsNothing(conferences) Then
Return NotFound()
End If
db.Conferences.Remove(conferences)
db.SaveChanges()
Return Ok(conferences)
End Function
Protected Overrides Sub Dispose(ByVal disposing As Boolean)
If (disposing) Then
db.Dispose()
End If
MyBase.Dispose(disposing)
End Sub
Private Function ConferencesExists(ByVal id As Integer) As Boolean
Return db.Conferences.Count(Function(e) e.AppointmentID = id) > 0
End Function
End Class
End Namespace

entity framework retrieve data as list(of string)

I have the following code to select all counties given a stateid from a counties table.
Public Shared Function GetCountiesfromState(statename As String) As List(Of String)
Dim context As New Model.teckEntities()
Dim query = From c In context.counties Where c.stateId = 7 Select c
Return query.ToList()
End Function
I get any error that query is returning a list of model. any thoughts on where the error lies?
If there is a Name (or Title) field on the County entity, it should be as simple as:
Public Shared Function GetCountiesfromState(statename As String) As List(Of String)
Dim context As New Model.teckEntities()
' Here is the difference:
Dim query = From c In context.counties Where c.stateId = 7 Select c.Name
Return query.ToList()
End Function
In your code above you were selecting the c which, is a County entity, not necessarily a string property. By selecting c.Name (or c.Title) instead, you'll be building a list of strings instead of a list of county entities.
Cheers.